Forem

Harsh Mishra
Harsh Mishra

Posted on

Mongoose with MongoDB

Complete Guide to Mongoose with MongoDB: A Comprehensive Tutorial

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a schema-based approach to working with MongoDB, allowing developers to define models with built-in validation, middleware, and query-building capabilities. This guide will take you through everything you need to know about using Mongoose with MongoDB, from setup to advanced queries, relationships, and deployment.


Table of Contents

  1. Introduction to Mongoose
  2. Why Use Mongoose with MongoDB?
  3. Setting Up Mongoose with MongoDB
  4. Understanding Mongoose Schema & Models
  5. CRUD Operations with Mongoose
  6. Querying Data in Mongoose
  7. Working with Relations in Mongoose
  8. Using Middleware in Mongoose
  9. Validation and Custom Validators
  10. Working with Transactions
  11. Seeding the Database
  12. Performance Optimization
  13. Error Handling in Mongoose
  14. Deploying Mongoose with MongoDB
  15. Conclusion

1. Introduction to Mongoose

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides:

Schema-based models for defining document structure.

Built-in validation for data integrity.

Middleware hooks for handling pre/post operations.

Advanced query building for efficient data retrieval.

Relationship handling to model complex data structures.

Mongoose makes working with MongoDB more structured and organized, making it a popular choice for Node.js developers.


2. Why Use Mongoose with MongoDB?

MongoDB is a NoSQL database that stores data in JSON-like documents. Mongoose provides a structured way to interact with MongoDB by offering:

🔹 Schema Definition – Defines structure and types for documents.

🔹 Data Validation – Ensures data integrity before saving.

🔹 Query Helpers – Makes queries more readable and efficient.

🔹 Middleware Hooks – Allows logic before and after database actions.

🔹 Relationship Handling – Enables population and referencing of documents.


3. Setting Up Mongoose with MongoDB

Step 1: Install Node.js and MongoDB

Ensure Node.js and MongoDB are installed. You can download MongoDB from:

🔗 MongoDB Download

Start MongoDB:

mongod --dbpath /data/db
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize a Node.js Project

mkdir my-mongoose-app
cd my-mongoose-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 3: Install Mongoose

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

Step 4: Connect Mongoose to MongoDB

Create a file db.js:

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
  .then(() => console.log("MongoDB connected successfully!"))
  .catch(err => console.error("MongoDB connection error:", err));
Enter fullscreen mode Exit fullscreen mode

4. Understanding Mongoose Schema & Models

A Schema defines the structure of a document. A Model is an instance of a schema that interacts with the database.

Example User Schema:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age: { type: Number, min: 18 },
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

module.exports = User;
Enter fullscreen mode Exit fullscreen mode

5. CRUD Operations with Mongoose

1. Create a User

const newUser = new User({ name: "Alice", email: "alice@example.com", age: 25 });
await newUser.save();
console.log("User created:", newUser);
Enter fullscreen mode Exit fullscreen mode

2. Read Users

const users = await User.find();
console.log(users);
Enter fullscreen mode Exit fullscreen mode

3. Update a User

const updatedUser = await User.findOneAndUpdate(
  { email: "alice@example.com" },
  { age: 30 },
  { new: true }
);
console.log(updatedUser);
Enter fullscreen mode Exit fullscreen mode

4. Delete a User

await User.deleteOne({ email: "alice@example.com" });
console.log("User deleted");
Enter fullscreen mode Exit fullscreen mode

6. Querying Data in Mongoose

Find Users Older than 21

const users = await User.find({ age: { $gt: 21 } });
Enter fullscreen mode Exit fullscreen mode

Find a Single User

const user = await User.findOne({ email: "alice@example.com" });
Enter fullscreen mode Exit fullscreen mode

Sorting & Limiting Results

const users = await User.find().sort({ age: -1 }).limit(5);
Enter fullscreen mode Exit fullscreen mode

7. Working with Relations in Mongoose

One-to-Many Relationship (User → Posts)

const postSchema = new mongoose.Schema({
  title: String,
  content: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: "User" }
});

const Post = mongoose.model("Post", postSchema);
Enter fullscreen mode Exit fullscreen mode

Fetching related data:

const posts = await Post.find().populate("author");
Enter fullscreen mode Exit fullscreen mode

8. Using Middleware in Mongoose

Mongoose supports pre and post middleware hooks.

Pre-save Hook

userSchema.pre('save', function(next) {
  console.log("Before saving:", this);
  next();
});
Enter fullscreen mode Exit fullscreen mode

Post-save Hook

userSchema.post('save', function(doc) {
  console.log("User saved:", doc);
});
Enter fullscreen mode Exit fullscreen mode

9. Validation and Custom Validators

Mongoose provides built-in validation like required, unique, and minLength.

Example custom validator:

const emailValidator = (email) => email.includes("@");

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    validate: [emailValidator, "Invalid email format"]
  }
});
Enter fullscreen mode Exit fullscreen mode

10. Working with Transactions

MongoDB supports transactions using session-based commits.

const session = await mongoose.startSession();
session.startTransaction();

try {
  const user = await User.create([{ name: "John" }], { session });
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
}
session.endSession();
Enter fullscreen mode Exit fullscreen mode

11. Seeding the Database

Create a seed.js file:

const mongoose = require('mongoose');
const User = require('./models/User');

async function seedDB() {
  await User.create({ name: "John Doe", email: "john@example.com", age: 30 });
  console.log("Database Seeded!");
}

seedDB().then(() => mongoose.disconnect());
Enter fullscreen mode Exit fullscreen mode

Run the seed file:

node seed.js
Enter fullscreen mode Exit fullscreen mode

12. Deploying Mongoose with MongoDB

Use MongoDB Atlas

MongoDB Atlas provides a cloud-based MongoDB database.

🔗 MongoDB Atlas

Set .env:

DATABASE_URL="mongodb+srv://your-user:password@cluster.mongodb.net/mydatabase"
Enter fullscreen mode Exit fullscreen mode

Modify db.js:

mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useUnifiedTopology: true });
Enter fullscreen mode Exit fullscreen mode

Conclusion

Mongoose provides a structured, type-safe, and efficient way to interact with MongoDB. With schema validation, relationships, middleware, transactions, and error handling, it simplifies database interactions while ensuring reliability. 🚀

Top comments (0)