Day 78 Mongoose ODM
Mongoose ek ODM (Object Document Mapper) hai jo MongoDB ke saath kaam asaan karta hai. Schemas, models, validation — sab Mongoose provide karta hai.
Mongoose Setup & Schema
Mongoose install aur model define karo.
// npm install mongoose
const mongoose = require("mongoose");
// Connect to MongoDB
mongoose.connect("mongodb://localhost:27017/myapp")
.then(() => console.log("MongoDB connected!"))
.catch(err => console.error("Connection error:", err));
// Schema define karo
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Name required hai"],
trim: true,
minlength: [2, "Name kam se kam 2 characters ka hona chahiye"]
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
match: [/^[^s@]+@[^s@]+.[^s@]+$/, "Valid email chahiye"]
},
age: {
type: Number,
min: [0, "Age negative nahi ho sakta"],
max: 150
},
role: {
type: String,
enum: ["user", "admin", "moderator"],
default: "user"
},
isActive: { type: Boolean, default: true },
createdAt: { type: Date, default: Date.now }
}, {
timestamps: true // createdAt aur updatedAt auto add
});
// Method add karo
userSchema.methods.getDisplayName = function() {
return `${this.name} (${this.role})`;
};
const User = mongoose.model("User", userSchema);
module.exports = User;
CRUD with Mongoose
Create, Read, Update, Delete operations.
const User = require("./user-model");
// CREATE
async function createUser(data) {
const user = new User(data);
return await user.save();
// OR: return await User.create(data);
}
// READ
async function getUsers() {
return await User
.find({ isActive: true })
.select("name email role") // sirf yeh fields
.sort({ createdAt: -1 }) // newest first
.limit(10);
}
async function findByEmail(email) {
return await User.findOne({ email });
}
// UPDATE
async function updateUser(id, updates) {
return await User.findByIdAndUpdate(
id,
{ $set: updates },
{ new: true, runValidators: true } // updated doc return karo
);
}
// DELETE
async function deleteUser(id) {
return await User.findByIdAndDelete(id);
}
🎯 Practice Challenge
Blog posts Mongoose model banao — title, content, author (ref to User), tags, published. Full CRUD API banao Express mein.