Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 70 ยท Drivers and applications

Mongoose and ODMs

Learn what an ODM like Mongoose adds to MongoDB: schemas, models, validation, middleware, populate and lean queries, and when it helps or gets in the way.

MongoDB itself does not force documents in a collection to look alike. That freedom is useful, and it is also how typos such as emial end up in production. An ODM (object-document mapper) is a library that sits on top of the driver and adds structure on the application side: a declared shape for your documents, validation before writes, default values, hooks that run around saves, and helpers for following references. In the Node.js world the best-known ODM is Mongoose. Python has MongoEngine and Beanie, Java has Spring Data MongoDB, and PHP has Doctrine ODM, but the ideas are the same.

This lesson uses Mongoose syntax in read-only blocks (it needs a real server) and gives you a runnable stand-in in plain JavaScript that implements the core ideas: a schema that validates and applies defaults, and hooks that run before a save. The stand-in is not Mongoose, and it is much smaller; it exists so you can see the mechanism execute. If you have not used the raw driver yet, start with Using MongoDB from Node.js; the language itself is covered in the JavaScript tutorial.

What an ODM adds

Schema A declared shape per collection.
Validation Bad data stops before the write.
Hooks Code that runs around save.
Populate Follow references for you.
1 / 2

Schemas and models

In Mongoose you describe a collection's documents with a schema, then compile it into a model, a class that talks to one collection.

JavaScript
import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
  name:   { type: String, required: true, trim: true },
  email:  { type: String, required: true, unique: true, lowercase: true },
  age:    { type: Number, min: 13, max: 120 },
  role:   { type: String, enum: ["user", "admin"], default: "user" },
  tags:   [String],
  joined: { type: Date, default: Date.now },
}, { timestamps: true });

const User = mongoose.model("User", userSchema);   // collection "users"

await mongoose.connect("mongodb://localhost:27017/app");
const ana = await User.create({ name: "Ana", email: "[email protected]" });
console.log(ana.role);    // "user" (default applied)
console.log(ana.email);   // "[email protected]" (lowercase setter applied)

A model gives you the familiar CRUD methods (find, findOne, findById, updateOne, deleteOne, countDocuments) plus instance methods such as doc.save(). Mongoose derives the collection name from the model name by lowercasing and pluralising it, which surprises people who expected User to produce a collection called User. You can override the name in the schema options.

Two caveats are worth knowing early. The unique: true option is not a validator: it asks MongoDB to build a unique index, and the violation surfaces as a duplicate-key error (code 11000) from the server. And the schema lives in your application code, so the database still accepts anything a different program, or the shell, sends. To make the database enforce rules itself, use Schema Validation.

Validation

Before a document is saved, Mongoose checks it against the schema. Built-in validators cover required, min and max (numbers and dates), minLength and maxLength, enum, and match (a regular expression). You can add your own with a validate function. Failed validation throws a ValidationError that lists every failing path, so you can report all problems at once.

JavaScript
try {
  await User.create({ name: "", email: "[email protected]", age: 7, role: "root" });
} catch (err) {
  console.log(err.name);                       // "ValidationError"
  console.log(Object.keys(err.errors));        // ["name", "age", "role"]
}

Validation runs on save() and create() by default. It does not run on updateOne or findOneAndUpdate unless you pass { runValidators: true }, and even then some validators behave differently because there is no full document to inspect. That is a classic source of invalid data slipping in through updates.

Here is a stand-in schema validator. The Schema class takes a definition, applies defaults and trimming, collects every error, and returns the cleaned document.

JS A schema that validates and applies defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first call shows the cleanup half of a schema (trimmed name, lowercased email, default role). The second shows the guard half: all four problems are reported together instead of one at a time.

Middleware (hooks)

Mongoose middleware are functions that run before or after an operation such as save, validate, find or deleteOne. Typical uses are hashing a password before saving, updating a slug, or writing an audit entry.

JavaScript
import bcrypt from "bcrypt";

userSchema.pre("save", async function () {
  if (this.isModified("password")) {
    this.password = await bcrypt.hash(this.password, 12);
  }
});

userSchema.post("save", function (doc) {
  console.log("saved user", doc._id);
});

Remember one trap: document middleware attached to save does not run for updateOne, updateMany or insertMany unless you register the matching query or model hook. If a rule must hold for every write, enforce it in more than one place or in the database.

The next stand-in adds pre and post hooks to a tiny model with an in-memory store, so you can watch the order of events.

JS Hooks around a save

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the failed save never reaches the post hook and never touches the store: validation sits between the two, just as in Mongoose. (A real password hook would hash inside pre; the stand-in hashes afterwards only to keep the output easy to read.)

Populate

MongoDB has no foreign keys, but you can store another document's _id and ask Mongoose to fetch it for you. populate runs a second query and swaps the id for the document in the result.

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

const posts = await Post.find().populate("author", "name email");
// each post.author is now { _id, name, email } instead of an ObjectId

That is convenient, but it is not a database join. Mongoose performs separate queries and stitches the results in Node, so populating a long list costs extra round trips. When you need joining inside the server, use Joining with $lookup, and ask first whether embedding the data would remove the need (Embedding vs Referencing).

Lean queries

By default, a Mongoose query returns full Mongoose documents: objects with change tracking, getters, virtuals and methods such as save(). That machinery costs memory and time. When you only need to read data, for example to send JSON from an API, add .lean() and receive plain JavaScript objects.

JavaScript
const users = await User.find({ role: "admin" }).lean();
// plain objects: faster and lighter, but no .save(), no virtuals, no defaults added

Lean results skip casting and defaults on the way out, so the shape is exactly what MongoDB stored. For list endpoints that return hundreds of documents, lean() is often the single easiest speedup.

When an ODM helps, and when it hurts

An ODM tends to pay off in applications with many models, several developers, and rules that need to be written once and shared: validation, defaults, hooks. It also gives editors something to autocomplete.

It tends to hurt when you run heavy aggregation pipelines (they bypass the schema anyway), when you move large volumes of data (the per-document overhead adds up), or when it hides what is happening, so that a simple line of code triggers several queries. Many teams use the plain driver for hot paths and reports and the ODM for ordinary application CRUD; others skip the ODM and validate at the database with $jsonSchema plus a small validation library such as Zod at the API edge. None of these is wrong. Choose deliberately, and still learn the raw operations in this tutorial, because every ODM method compiles down to them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Mongoose declares unique: true on a schema field. What actually enforces uniqueness?

    unique is a schema hint to build a unique index. The server enforces it and returns a duplicate-key error (code 11000); Mongoose does not run a validator for it.
  2. 2. Which statement about populate is correct?

    populate performs separate queries and stitches the results together in the application, so it costs extra round trips.
  3. 3. What does .lean() do to a Mongoose query?

    lean skips building full Mongoose documents. The result is faster and lighter but has no save(), virtuals or defaults.
  4. 4. Why might invalid data still reach a collection that has a Mongoose schema?

    The schema lives in the application. Other writers bypass it, and updates skip validators unless runValidators is set. Database-side validation closes the gap.

Summary

  • An ODM such as Mongoose adds an application-side schema, validation, defaults, hooks and reference helpers on top of the driver.
  • Schemas compile to models; unique builds an index rather than validating.
  • Validation runs on save/create by default and needs runValidators for updates; it reports every failing path.
  • Middleware (pre/post) is convenient but does not cover every write path.
  • populate is separate queries, not a join; lean() returns plain objects for faster reads.
  • Use an ODM where its structure pays off, the raw driver for hot paths, and database validation as a backstop.

Next, learn how to control who can do what in Authentication and Role-Based Access.