Mongoose — MongoDB ODM for Node.js
You are an expert in Mongoose, the elegant MongoDB object modeling library for Node.js. You help developers define schemas with validation, build queries with a fluent API, use middleware hooks, populate references, create virtual fields, and handle transactions — providing structure and type safety on top of MongoDB's flexible document model.
Core Capabilities
Schema Definition
import mongoose, { Schema, Document, Model } from "mongoose";
interface IUser extends Document {
email: string;
name: string;
passwordHash: string;
role: "user" | "admin" | "moderator";
profile: { bio?: string; avatar?: string; website?: string };
posts: mongoose.Types.ObjectId[];
createdAt: Date;
updatedAt: Date;
fullName: string;
}
const userSchema = new Schema<IUser>(
{
email: {
type: String,
required: [true, "Email is required"],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, "Invalid email format"],
},
name: { type: String, required: true, minlength: 2, maxlength: 100 },
passwordHash: { type: String, required: true, select: false },
role: { type: String, enum: ["user", "admin", "moderator"], default: "user" },
profile: {
bio: { type: String, maxlength: 500 },
avatar: String,
website: { type: String, match: /^https?:\/\// },
},
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
// Virtual field
userSchema.virtual("fullName").get(function () {
return this.name;
});
// Index for search
userSchema.index({ email: 1 });
userSchema.index({ name: "text", "profile.bio": "text" });
// Pre-save middleware
userSchema.pre("save", async function (next) {
if (this.isModified("passwordHash")) {
this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
}
next();
});
// Static method
userSchema.statics.findByEmail = function (email: string) {
return this.findOne({ email: email.toLowerCase() });
};
// Instance method
userSchema.methods.verifyPassword = async function (password: string) {
return bcrypt.compare(password, this.passwordHash);
};
const User: Model<IUser> = mongoose.model("User", userSchema);
Queries
// Find with filters, sorting, pagination
const users = await User.find({ role: "user" })
.sort({ createdAt: -1 })
.skip(20).limit(10)
.select("name email profile.avatar")
.lean(); // Plain objects (faster)
// Populate references
const userWithPosts = await User.findById(id)
.populate({ path: "posts", select: "title createdAt", options: { limit: 5, sort: { createdAt: -1 } } });
// Aggregation pipeline
const stats = await User.aggregate([
{ $match: { createdAt: { $gte: thirtyDaysAgo } } },
{ $group: { _id: "$role", count: { $sum: 1 }, latest: { $max: "$createdAt" } } },
{ $sort: { count: -1 } },
]);
// Transactions
const session = await mongoose.startSession();
await session.withTransaction(async () => {
const user = await User.create([{ name: "Alice", email: "alice@example.com", passwordHash: "..." }], { session });
await Post.create([{ title: "First Post", author: user[0]._id }], { session });
});
Installation
npm install mongoose
Best Practices
- Schema validation — Define strict schemas; use
required, enum, match, min/max validators
- Lean queries — Use
.lean() for read-only queries; returns plain objects, 5x faster than Mongoose documents
- Indexes — Add indexes for fields you query/sort by; use
explain() to verify query plans
- Population — Use
populate() sparingly; for complex joins, prefer aggregation $lookup
- Middleware — Use
pre('save') for hashing, validation; post('save') for notifications, logging
- Timestamps — Enable
timestamps: true; auto-manages createdAt and updatedAt
- Transactions — Use sessions for multi-document operations; requires replica set or MongoDB Atlas
- TypeScript — Define interfaces extending
Document; use generics with Schema<IUser> for full type safety
1---2name: mongoose3description: >-4 You are an expert in Mongoose, the elegant MongoDB object modeling library5 for Node.js. You help developers define schemas with validation, build6 queries with a fluent API, use middleware hooks, populate references, create7 virtual fields, and handle transactions — providing structure and type8 safety on top of MongoDB's flexible document model.9license: Apache-2.010compatibility: ''11metadata:12 source: https://skillmd.com/skills/eliferjunior/mongoose13 author: terminal-skills14 version: 1.0.015 category: Backend Development16 tags:17 - mongodb18 - odm19 - schema20 - validation21 - typescript22 - node23 - database24---2526# Mongoose — MongoDB ODM for Node.js2728You are an expert in Mongoose, the elegant MongoDB object modeling library for Node.js. You help developers define schemas with validation, build queries with a fluent API, use middleware hooks, populate references, create virtual fields, and handle transactions — providing structure and type safety on top of MongoDB's flexible document model.2930## Core Capabilities3132### Schema Definition3334```typescript35import mongoose, { Schema, Document, Model } from "mongoose";3637interface IUser extends Document {38 email: string;39 name: string;40 passwordHash: string;41 role: "user" | "admin" | "moderator";42 profile: { bio?: string; avatar?: string; website?: string };43 posts: mongoose.Types.ObjectId[];44 createdAt: Date;45 updatedAt: Date;46 fullName: string;47}4849const userSchema = new Schema<IUser>(50 {51 email: {52 type: String,53 required: [true, "Email is required"],54 unique: true,55 lowercase: true,56 trim: true,57 match: [/^\S+@\S+\.\S+$/, "Invalid email format"],58 },59 name: { type: String, required: true, minlength: 2, maxlength: 100 },60 passwordHash: { type: String, required: true, select: false },61 role: { type: String, enum: ["user", "admin", "moderator"], default: "user" },62 profile: {63 bio: { type: String, maxlength: 500 },64 avatar: String,65 website: { type: String, match: /^https?:\/\// },66 },67 posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],68 },69 {70 timestamps: true,71 toJSON: { virtuals: true },72 toObject: { virtuals: true },73 },74);7576// Virtual field77userSchema.virtual("fullName").get(function () {78 return this.name;79});8081// Index for search82userSchema.index({ email: 1 });83userSchema.index({ name: "text", "profile.bio": "text" });8485// Pre-save middleware86userSchema.pre("save", async function (next) {87 if (this.isModified("passwordHash")) {88 this.passwordHash = await bcrypt.hash(this.passwordHash, 12);89 }90 next();91});9293// Static method94userSchema.statics.findByEmail = function (email: string) {95 return this.findOne({ email: email.toLowerCase() });96};9798// Instance method99userSchema.methods.verifyPassword = async function (password: string) {100 return bcrypt.compare(password, this.passwordHash);101};102103const User: Model<IUser> = mongoose.model("User", userSchema);104```105106### Queries107108```typescript109// Find with filters, sorting, pagination110const users = await User.find({ role: "user" })111 .sort({ createdAt: -1 })112 .skip(20).limit(10)113 .select("name email profile.avatar")114 .lean(); // Plain objects (faster)115116// Populate references117const userWithPosts = await User.findById(id)118 .populate({ path: "posts", select: "title createdAt", options: { limit: 5, sort: { createdAt: -1 } } });119120// Aggregation pipeline121const stats = await User.aggregate([122 { $match: { createdAt: { $gte: thirtyDaysAgo } } },123 { $group: { _id: "$role", count: { $sum: 1 }, latest: { $max: "$createdAt" } } },124 { $sort: { count: -1 } },125]);126127// Transactions128const session = await mongoose.startSession();129await session.withTransaction(async () => {130 const user = await User.create([{ name: "Alice", email: "alice@example.com", passwordHash: "..." }], { session });131 await Post.create([{ title: "First Post", author: user[0]._id }], { session });132});133```134135## Installation136137```bash138npm install mongoose139```140141## Best Practices1421431. **Schema validation** — Define strict schemas; use `required`, `enum`, `match`, `min/max` validators1442. **Lean queries** — Use `.lean()` for read-only queries; returns plain objects, 5x faster than Mongoose documents1453. **Indexes** — Add indexes for fields you query/sort by; use `explain()` to verify query plans1464. **Population** — Use `populate()` sparingly; for complex joins, prefer aggregation `$lookup`1475. **Middleware** — Use `pre('save')` for hashing, validation; `post('save')` for notifications, logging1486. **Timestamps** — Enable `timestamps: true`; auto-manages `createdAt` and `updatedAt`1497. **Transactions** — Use sessions for multi-document operations; requires replica set or MongoDB Atlas1508. **TypeScript** — Define interfaces extending `Document`; use generics with `Schema<IUser>` for full type safety