Databases & Data Access
Node.js MongoDB with Mongoose
Mongoose is the standard object-modelling library for MongoDB in Node. It adds schemas, validation, type casting, middleware hooks and query helpers on top of the MongoDB driver.
What is MongoDB with Mongoose in Node.js?
Mongoose is the standard object-modelling library for MongoDB in Node. It adds schemas, validation, type casting, middleware hooks and query helpers on top of the MongoDB driver.
MongoDB with Mongoose example
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGODB_URI, {
maxPoolSize: 20,
serverSelectionTimeoutMS: 5000,
});
const jobSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true, index: true },
company: { type: String, required: true },
city: { type: String, index: true },
stipend: { type: Number, min: 0 },
status: { type: String, enum: ['active', 'closed'], default: 'active' },
postedBy:{ type: mongoose.Schema.Types.ObjectId, ref: 'User' },
}, { timestamps: true });
jobSchema.index({ city: 1, status: 1, createdAt: -1 }); // compound index
export const Job = mongoose.model('Job', jobSchema);How this works
timestamps adds createdAt and updatedAt automatically. The compound index matches the shape of the most common query — filter by city and status, sort by date — which is what keeps the query fast as the collection grows.
Key points to remember
- Connect once at startup, not per request — Mongoose pools connections.
- Schema validation runs on save and on validated updates, not on raw driver writes.
- lean() returns plain objects instead of documents and is much faster for read-only queries.
- Model names are singular; Mongoose pluralises the collection name.
Common mistakes with MongoDB with Mongoose
- Calling connect inside a request handler, opening a new pool each time.
- Querying an unindexed field on a large collection, causing a full scan.
- Forgetting await on a query, then operating on a Query object.
Node.js MongoDB with Mongoose— Interview Questions & FAQs
Do I need Mongoose, or can I use the MongoDB driver directly?+
The driver is enough for simple scripts. Mongoose is worth it in applications for schema validation, population, hooks and a more ergonomic query API.
