Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 133 ยท Data and Storage

MongoDB with Mongoose: Schemas, Models, Queries and Populate

Learn Mongoose, the Node.js ODM for MongoDB. Define schemas and models, validate data, query and populate references, use hooks and virtuals, and run a mini-Mongoose in the editor.

MongoDB and Redis from Node showed the official driver, which stores whatever documents you hand it. That freedom is also the risk: a typo such as emial creates a new field and nothing complains, and every query has to remember what shape a "user" is supposed to have.

Mongoose is an ODM (object-document mapper) that puts a layer of structure on top of MongoDB. You declare a schema (the fields, their types and rules), compile it into a model (a class for one collection), and use the model to create, validate, query and update documents. It also adds middleware hooks, virtual fields and populate, which resolves references between collections in a join-like way. It is the most widely used MongoDB library in the Node.js world, so you will meet it in many existing code bases.

There is no database server and no npm install in our editor, so the real code here is read-only. To run the core ideas, you will build a mini-Mongoose against an in-memory array, with the same method names. It is a teaching model: it shows what the layer does, not how the real driver talks to a server.

Connecting and defining a schema

Terminal
npm install mongoose
JavaScript
import mongoose from 'mongoose';

await mongoose.connect(process.env.MONGODB_URI);     // e.g. mongodb://127.0.0.1:27017/shop

const userSchema = new mongoose.Schema(
  {
    name:  { type: String, required: [true, 'name is required'], trim: true, minlength: 2 },
    email: { type: String, required: true, unique: true, lowercase: true, match: /^\S+@\S+\.\S+$/ },
    role:  { type: String, enum: ['user', 'admin'], default: 'user' },
    age:   { type: Number, min: 0, max: 130 },
  },
  { timestamps: true },                                 // adds createdAt and updatedAt
);

export const User = mongoose.model('User', userSchema); // collection name: "users"

Every field is a small object with a type and optional validators and setters: required, min/max, minlength, enum, match, trim, lowercase, default, and your own validate: { validator, message }. Two things people mix up: unique: true is not a validator. It creates a unique index in MongoDB, and the error comes from the database (code 11000), not from Mongoose's validation step. And a schema describes what Mongoose will accept; the database itself does not enforce it unless you add a server-side validator.

What validation does, run it

Before saving, a model runs the schema over the document: apply defaults and setters, then check every rule, and collect all failures in one ValidationError. This part you can see without a database:

Node.js Schema rules, defaults and a collected ValidationError

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the good document comes back cleaned (name trimmed, email lowercased, role defaulted), and that the bad one reports four problems at once. Real Mongoose does exactly this in doc.validate(), which save() calls for you. Unknown fields such as isAdmin are dropped from the saved document by default (strict mode), which protects you from a client sending extra fields.

Documents, queries and the model methods

With a connected model you use a small set of methods all day:

JavaScript
const ada = await User.create({ name: 'Ada', email: '[email protected]' });   // validate + insert

const admins = await User.find({ role: 'admin', age: { $gte: 18 } })
  .sort({ createdAt: -1 })
  .limit(10)
  .select('name email')
  .lean();                       // plain objects instead of full documents: faster, read-only data

const one = await User.findById(id);                          // null when missing
await User.updateOne({ _id: id }, { $set: { role: 'admin' } });
const updated = await User.findByIdAndUpdate(id, { age: 37 }, { new: true, runValidators: true });
await User.deleteOne({ _id: id });
const total = await User.countDocuments({ role: 'user' });

Details that cost people hours: find returns an array (empty when nothing matches) while findOne and findById return a document or null, so always handle null; update methods skip validators unless you pass runValidators: true; lean() objects have no methods, virtuals or save(); and a query is a lazy object that only runs when you await it, so forgetting await is a silent bug.

Hooks, virtuals, methods and populate

Four features turn a schema into a small domain model:

  • Hooks (schema.pre('save', fn) and post) run around operations. The classic use is hashing a password before saving, or setting a slug from a title.
  • Virtuals are computed properties that are not stored: fullName, isExpired.
  • Instance and static methods (schema.methods.verifyPassword, schema.statics.findByEmail) keep related behaviour on the model.
  • Populate replaces a stored reference (an ObjectId) with the referenced document. MongoDB has no joins in find; Mongoose runs a second query and stitches the result for you.
Node.js A mini-Mongoose: model, hook, virtual, query and populate

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The shape is Mongoose's: pre('save') runs before the document is stored (so the hook can hash the password and delete the plain text), the virtual label is computed on read and never stored, find() returns a lazy query you can chain and await, and populate('author') swaps the stored id for the user's document. In real Mongoose, .populate issues a second query (find({ _id: { $in: ids } })), so populating a large list is two round trips, not N.

Using Mongoose in an application

  • Connect once, at start-up, and handle connection errors; Mongoose buffers commands until it is connected, which can hide a wrong URI as a timeout. Close the connection on shutdown (see Graceful Shutdown).
  • Validate at the edge too. Schema validation protects the database, but request validation (see Validation) gives the client a clean 400 before you get there.
  • Index what you query. schema.index({ email: 1 }, { unique: true }), and check slow queries with .explain(). Remember the database enforces uniqueness, so catch error code 11000 and answer 409.
  • Use lean() for read-only endpoints that serialize straight to JSON.
  • Do not embed unbounded arrays. A post with a million comments inside one document hits MongoDB's 16 MB document limit; reference instead.
  • Know when an ODM is not the answer. Mongoose is great for document-shaped data. If you need heavy joins and transactions across many tables, a relational database with an ORM (see ORMs: Prisma and Sequelize) is a better fit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does unique: true in a Mongoose schema do?

    unique is an index option, not a validator. A duplicate is rejected by MongoDB with error code 11000, which your code must catch.
  2. 2. What is the difference between find() and findOne()?

    find always gives an array (possibly empty). findOne and findById give a single document, or null when nothing matches.
  3. 3. What does populate('author') do?

    MongoDB find has no joins, so Mongoose reads the referenced ids, fetches those documents with a second query and puts them in the result.
  4. 4. Why might findByIdAndUpdate accept an invalid age even though the schema has max: 130?

    Validators run on save by default. For update queries you must opt in with runValidators: true.
  5. 5. Why is lean() useful on a read-only endpoint?

    Lean results skip document creation, so no getters, virtuals or save(), but they serialize to JSON quickly.

Summary

  • Mongoose adds schemas, validation, hooks, virtuals, methods and populate on top of the MongoDB driver.
  • A schema defines fields and rules; mongoose.model('User', schema) gives a model for the users collection.
  • Validation runs on save(), collects every error, and cleans values (defaults, trim, lowercase); update queries need runValidators: true.
  • find gives an array, findOne gives a document or null; queries are lazy until awaited; lean() returns plain objects.
  • pre('save') hooks suit password hashing; virtuals are computed, not stored; populate is a second query.
  • Index what you query, handle duplicate-key errors, and reference instead of embedding unbounded data.

Next: Sending Email with Nodemailer.