Sitemap

Mongoose:

3 min readOct 3, 2025

--

Mongoose ek ODM (Object Data Modeling) library hai jo MongoDB aur Node.js ke liye use hoti hai

  • MongoDB normally schema-less hota hai (yani tum chaaho to kuch bhi structure save kar sakte ho).

. Lekin ye problem bhi ban sakta hai kyunki inconsistent data save ho jata hai.

👉 Yahan Mongoose help karta hai:

  • Schema (blueprint ke taur par)
  • Validation (data check karne ke liye)
  • Middleware (functions jo automatically chalte hain before/after actions)
  • Easy queries likhne ka tariqa

1. Connection

Sabse pehle MongoDB se connect karna hota hai:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => console.log("MongoDB connected"))
.catch(err => console.error(err));

. Schema

Schema ek blueprint hai jo define karta hai ke tumhara data kaisa hoga.

Example:

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

3. Model

Schema se hum Model banate hain jo database collection ko represent karta hai.

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

👉 “User” model MongoDB me users collection banayega.

4. Document

Document basically ek record hota hai.

const user = new User({
name: "Nimra",
age: 22,
email: "nimra@example.com"
});
await user.save();

5. CRUD Operations

  • Create
await User.create({ name: "Ali", age: 25, email: "ali@example.com" });
  • Read
const users = await User.find();
const oneUser = await User.findOne({ name: "Nimra" });
  • Update
await User.updateOne({ name: "Ali" }, { $set: { age: 26 } });
  • Delete
await User.deleteOne({ name: "Ali" });

6. Middleware (Hooks)

Ye functions hote hain jo kisi action se pehle ya baad me chalte hain.

Get Nimra Kosar’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

userSchema.pre('save', function(next) {
console.log("Saving user:", this.name);
next();
});

👉 Mostly password hash karne ke liye use hota hai.

7. Virtuals

Ye fields DB me save nahi hoti lekin calculate ho jati hain jab tum use call karte ho.

userSchema.virtual('fullName').get(function() {
return this.firstName + " " + this.lastName;
});

8. Population (Relationships)

Ek collection ko doosri collection se connect karne ke liye.

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

Phir:

const posts = await Post.find().populate('author');

👉 Author ki ID ke jagah pura User object mil jaata hai.

9. Aggregation

Complex calculations/reporting ke liye.

const stats = await User.aggregate([
{ $match: { age: { $gte: 18 } } },
{ $group: { _id: null, avgAge: { $avg: "$age" } } }
]);

📌 Advantages of Mongoose

✅ Schema enforce karta hai → data clean aur consistent hota hai
✅ Validation aur default values built-in hoti hain
✅ CRUD operations easy ho jate hain
✅ Relationships handle karne ke liye populate() hai
✅ Middleware support hai

📌 Disadvantages of Mongoose

⚠️ Thoda slow hota hai compared to raw MongoDB driver
⚠️ Advanced MongoDB features kabhi tricky lagte hain
⚠️ Kabhi kabhi flexibility kam ho jati hai

📌 MERN Stack me Mongoose ka role

  • React (Frontend): API call bhejta hai (Axios, fetch)
  • Express/Node (Backend): API handle karta hai
  • Mongoose: MongoDB ke sath interact karta hai
  • MongoDB: Data store karta hai

📌 Next Steps for You

  1. npm install mongoose karo
  2. Ek schema banao (User)
  3. CRUD operations practice karo
  4. Middleware add karo (password hashing)
  5. Relationships ke liye populate try karo
  6. Aggregation explore karo

--

--