Mongoose: What It Adds and What It Hides
Mongoose is a Node.js library on top of the MongoDB driver that adds schemas, models, checks before every save, defaults and populate, and it also changes your data and runs queries without saying so, so this lesson shows both sides.
Journeyman · MongoDB · Node.js · Updated
After this lesson you can
- Define a Mongoose schema and model with required fields, an enum, a default and a reference, and predict what create saves or refuses
- Explain what Mongoose hides, from casting and dropped fields to updates that skip validation and populate's second query
- Choose between Mongoose and the plain driver for a project, and between lean() and full Mongoose documents for a route
Key takeaways
- Mongoose sits on top of the official driver. A schema describes one kind of document, and mongoose.model turns it into a model that saves and finds them.
- Rules such as required, enum and min are checked in your app before a save, defaults are filled in, and a broken rule stops the save with a ValidationError.
- find gives back Mongoose documents with methods such as save, while lean() gives back plain objects, which is lighter for a route that only reads.
- populate fills in a reference with a second query that your app runs, not with a $lookup inside the database.
- Mongoose turns "3" into 3, drops fields the schema doesn't name, and lets updateOne skip the schema's rules unless you pass runValidators.
Open the data code of a Node project at a new job, or follow an Express tutorial, and you may find Pet.findById(id) where you expected db.collection("pets").findOne(...). That's Mongoose, a library many Node projects use with MongoDB. This lesson shows what it gives you and, equally important, what it does without telling you, so you can work in a Mongoose project and choose for your own.
The examples use the Maple Street Pet Adoption Center's pets, in a project folder whose .env file holds MONGODB_URI, as in Connecting from Node: MongoClient and the Connection String. They keep to a practice database of their own, maple_street_mongoose, so the pets your API uses stay as they are. This course uses Mongoose 9.12.2:
npm install mongoose@9.12.2
The driver saves whatever you hand it
With the driver, every rule about a pet is yours to write: a name is required, the shelter takes dogs, cats and rabbits, an age can't be negative. Forget one check in the data layer, and the driver stores { specis: "dog", age: -2 } as happily as a real pet. A $jsonSchema validator, from Schema Validation with $jsonSchema, is one answer, kept in the database.
Mongoose's answer is to describe each kind of document once, in your code, and check every save against that description. A library that maps your program's objects to database documents and back is called an object document mapper, or ODM. Mongoose is an ODM for MongoDB in Node.js, and underneath it runs on the same official driver.
A schema, a model, and checks before the save
Think of the shelter's intake form: a line for the name, boxes to tick for the species, a status that starts as "available". A schema is that form for one kind of document. Make models/pet.js:
import mongoose from "mongoose";
const petSchema = new mongoose.Schema({
name: { type: String, required: true },
species: { type: String, required: true, enum: ["dog", "cat", "rabbit"] },
age: { type: Number, min: 0 },
traits: [String],
status: { type: String, enum: ["available", "pending", "adopted"], default: "available" },
});
export const Pet = mongoose.model("Pet", petSchema);
required means the field must be there, enum (short for enumeration, a list of the allowed values) means it must be one of these, min sets the lowest number, and default fills in a value when none is given. mongoose.model("Pet", petSchema) makes a model, the object you save and find pets with, in a collection Mongoose names for you: pets, lowercased and plural. Make add-a-pet.js:
import mongoose from "mongoose";
import { Pet } from "./models/pet.js";
await mongoose.connect(process.env.MONGODB_URI, { dbName: "maple_street_mongoose" });
const biscuit = await Pet.create({ name: "Biscuit", species: "dog", age: "3", traits: ["good with kids", "house-trained"], color: "brown" });
console.log(biscuit);
await mongoose.disconnect();
node --env-file=.env add-a-pet.js
{
name: 'Biscuit',
species: 'dog',
age: 3,
traits: [ 'good with kids', 'house-trained' ],
status: 'available',
_id: new ObjectId('6afca2b3a40edb3cf3d0e6df'),
__v: 0
}
create does the job of insertOne, and the status was filled in by the default. Look closely, too: three things changed, and the next sections come back to them. Now a pet with three mistakes, in bad-pet.js:
import mongoose from "mongoose";
import { Pet } from "./models/pet.js";
await mongoose.connect(process.env.MONGODB_URI, { dbName: "maple_street_mongoose" });
try {
await Pet.create({ species: "parrot", age: -1 });
} catch (error) {
console.log(error.name);
for (const field in error.errors) {
console.log(`${field}: ${error.errors[field].message}`);
}
}
await mongoose.disconnect();
ValidationError
name: Path `name` is required.
species: `parrot` is not a valid enum value for path `species`.
age: Path `age` (-1) is less than minimum allowed value (0).
A ValidationError names every broken rule, and nothing reached MongoDB. Keep in mind where the rules live: in your app. mongosh, Compass or another program writing to the same collection never sees them.
Documents with methods, lean() and populate
findOne and find give back Mongoose documents: your data with methods attached, such as save(). lean() asks for plain objects instead, which are lighter and fine for a route that only reads. In documents-and-lean.js:
import mongoose from "mongoose";
import { Pet } from "./models/pet.js";
await mongoose.connect(process.env.MONGODB_URI, { dbName: "maple_street_mongoose" });
const pet = await Pet.findOne({ name: "Biscuit" });
pet.status = "pending";
await pet.save();
console.log(pet.status, pet instanceof mongoose.Document);
const plain = await Pet.findOne({ name: "Biscuit" }).lean();
console.log(plain.status, plain instanceof mongoose.Document);
await mongoose.disconnect();
pending true
pending false
save() runs the schema's checks again before it writes. A reference to another document is a field with ref, naming the model it points to. Make models/application.js:
import mongoose from "mongoose";
const applicationSchema = new mongoose.Schema({
applicant: { type: String, required: true },
pet: { type: mongoose.Schema.Types.ObjectId, ref: "Pet", required: true },
});
export const Application = mongoose.model("Application", applicationSchema);
populate("pet", "name species") swaps the stored id for the pet's name and species. In populate.js, mongoose.set("debug", true) prints every query Mongoose sends:
import mongoose from "mongoose";
import { Pet } from "./models/pet.js";
import { Application } from "./models/application.js";
await mongoose.connect(process.env.MONGODB_URI, { dbName: "maple_street_mongoose" });
const biscuit = await Pet.findOne({ name: "Biscuit" });
await Application.create({ applicant: "Rosa", pet: biscuit._id });
mongoose.set("debug", true);
const applications = await Application.find().populate("pet", "name species").lean();
console.log(applications);
await mongoose.disconnect();
Mongoose: applications.find({}, {})
Mongoose: pets.find({ _id: { '$in': [ ObjectId("6afca2b3a40edb3cf3d0e6df") ] } }, { projection: { name: 1, species: 1 } })
[
{
_id: new ObjectId('6afca2b4201fdc9fc629d8dd'),
applicant: 'Rosa',
pet: {
_id: new ObjectId('6afca2b3a40edb3cf3d0e6df'),
name: 'Biscuit',
species: 'dog'
},
__v: 0
}
]
Two queries: the applications, then the pets they name. That's the same join as $lookup: Bringing in Related Documents, but done by your app, one extra trip to the database for each populate. Your ids will be different.

What it hides
Back to Biscuit's output. You sent the age as the text "3", and Mongoose stored the number 3: it casts values to the schema's types. You sent color: "brown", and it's gone: fields the schema doesn't name are dropped, with no error. And __v, read "underscore v", is a version number Mongoose adds to every document. One more, in updates-skip-checks.js:
import mongoose from "mongoose";
import { Pet } from "./models/pet.js";
await mongoose.connect(process.env.MONGODB_URI, { dbName: "maple_street_mongoose" });
await Pet.updateOne({ name: "Biscuit" }, { status: "sleeping" });
const biscuit = await Pet.findOne({ name: "Biscuit" }).lean();
console.log(biscuit.status);
try {
await Pet.updateOne({ name: "Biscuit" }, { status: "napping" }, { runValidators: true });
} catch (error) {
console.log(error.name);
}
await mongoose.disconnect();
sleeping
ValidationError
"sleeping" isn't in the enum, yet updateOne saved it: updates skip the schema's rules unless you pass runValidators: true, or change the document and call save().
Mongoose or the plain driver?
| The plain driver | Mongoose | |
|---|---|---|
| Rules for a document | your code, or $jsonSchema in the database |
the schema, checked in your app |
| What comes back | plain objects | documents with methods, or plain with lean() |
| Related documents | $lookup, one query |
populate, a second query |
| Surprises | few: it sends what you write | casting, dropped fields, __v, updates without checks |
Mongoose fits a project with many kinds of document whose rules belong in one place, and a team that already knows it. The plain driver fits when you want to see exactly what reaches the database, and it's what Mongoose runs on, which is why this course taught it first. For a route that only reads, add lean().
Check yourself
2 questions to try on the lesson page.
So what
Mongoose saves you from writing the same checks over and over, and it also changes your data in quiet ways. Knowing both sides is what lets you trust a Mongoose project, or decide you'd rather not use it.