skip to content

Mongoose

MongoDB's ODM for Node: schemas and models layered over a schemaless store, validation, pre/post middleware, and populate for cross-document references. Interviewers ask about it to test whether you understand that Mongoose — not MongoDB — enforces the schema, and what populate really costs in round trips.

on this pageshow

explore

questions

6

With Mongoose 9, what does a schema add on top of a MongoDB collection, and where is that schema actually enforced?

level: juniorimportance: must knowfreq 78%

answer

  1. who checks the shape
  2. cast before validate
  3. CastError versus ValidatorError
  4. strict mode and undeclared keys
  5. model class, document instance

basics

~20 s

A Mongoose schema declares each field's type, validators, defaults and options, and Mongoose casts and validates documents inside your Node process before writing them. MongoDB itself never sees that schema, so any writer that bypasses Mongoose bypasses it too.

solid answer

~40 s

A schema maps paths to SchemaTypes with options such as `required`, `enum`, `min` and `default`, plus schema options like `timestamps`. `mongoose.model('Order', orderSchema)` compiles it into a model class, and each `new Order({...})` is a document. On `save()` Mongoose first **casts** values (`'42.5'` becomes a number, a 24-character hex string becomes an `ObjectId`) and records a `CastError` when it cannot, then runs **validators** and rejects with a `ValidationError` that lists every failing path. Strict mode, on by default, leaves undeclared keys out of what it writes. All of this runs in the application: the server stores whatever reaches it, so the bare driver, a shell or another service skips the schema entirely, and update queries skip validators unless you pass `runValidators`.

code

javascript · 30 lines
javascript
const mongoose = require('mongoose');
const { Schema } = mongoose;

const orderSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  status: { type: String, enum: ['pending', 'paid', 'shipped'], default: 'pending' },
  total: { type: Number, min: 0, required: true }
}, { timestamps: true });

const Order = mongoose.model('Order', orderSchema);

async function main() {
  const ok = new Order({ user: '64b7f0c2a1b2c3d4e5f60718', total: '42.5', coupon: 'X' });
  console.log(typeof ok.total, ok.status, ok.get('coupon')); // number pending undefined

  const bad = new Order({ user: 'nope', total: -1, status: 'lost' });
  try {
    await bad.validate(); // no database needed
  } catch (err) {
    console.log(err.name); // ValidationError
    for (const [path, e] of Object.entries(err.errors)) {
      console.log(path, e.name, e.kind);
    }
    // user CastError ObjectId
    // status ValidatorError enum
    // total ValidatorError min
  }
}

main();

go deeper

for a junior

Know the three objects: schema declares shape, model is the compiled class, document is one instance. Be able to list required, enum, min and default, and say that casting happens before validation.

for a middle

Explain the save pipeline in order: cast, validate as the first pre-save step, then your own hooks and the write. Distinguish CastError from ValidatorError and say what strict mode does with undeclared keys.

for a senior

Point out every way data reaches the collection without the schema: the bare driver, other services, update queries without runValidators, and old documents. Know that unique builds an index rather than validating.

for a principal

Treat the schema as an application contract, not a database guarantee. Be ready to say which invariants also need server-side enforcement because several services or tools write to the same collection.

## What problem a schema solves MongoDB stores **documents**, and a collection does not require them to share a shape unless the database is configured to. That flexibility means nothing stops one request from writing `total: "42"` as a string and the next from writing `total: 42` as a number, after which every query and report has to cope with both. **Mongoose** is an object-document mapper (ODM) for Node: it puts a declared shape in front of the collection, inside your application. ## Schema, model and document Three objects carry that shape: - A **schema** (`new Schema({...})`) lists the paths a document may have and, for each, a **SchemaType** such as `String`, `Number`, `Date` or `Schema.Types.ObjectId`, plus options. - A **model** is the class Mongoose compiles from a schema with `mongoose.model('Order', orderSchema)`. Its statics run queries against one collection: `Order.find()`, `Order.create()`, `Order.updateOne()`. - A **document** is one instance of that class, either built with `new Order({...})` or loaded by a query. It tracks which paths changed and knows how to `save()` itself. Hooks and plugins must be added to the schema **before** the model is compiled, because the model is built from the schema as it stands at that moment. ## What a schema can declare | Declaration | What Mongoose does with it | |---|---| | `type` | casts incoming values to that type, or records a `CastError` | | `required` | fails validation when the value is missing | | `enum`, `match`, `minLength`, `maxLength` | string validators | | `min`, `max` | number validators | | `validate` | runs your own function, sync or async | | `default` | fills the path when it is undefined | | `ref` | names the model `populate()` should load | | `timestamps` (schema option) | sets `createdAt` and `updatedAt` for you | ## The order things happen in When you call `save()` (or `create()`, which saves each document): 1. **Casting** converts each value to its SchemaType. A value that cannot be converted, such as `'nope'` for an `ObjectId` path, becomes a `CastError` for that path, and that path's validators do not run. 2. **Validation** runs as the first `pre('save')` step. Built-in and custom validators run on every path that has a value, and `required` also runs on missing ones. Validators other than `required` skip undefined values. 3. Any failure rejects `save()` with one `ValidationError` whose `errors` object is keyed by path; each entry is a `CastError` or a `ValidatorError` with a `kind` such as `enum` or `min`. 4. Only after that do your own `pre('save')` hooks run, and then the write is sent. You can run steps 1 to 3 without a database by calling `await doc.validate()`. **Strict mode** (the `strict` schema option, `true` by default) adds a quieter rule: keys the schema does not declare are left out of the document Mongoose writes. Setting `strict: 'throw'` turns that into an error instead. ## Where the enforcement actually lives Every rule above runs in your Node process, at the moment Mongoose builds or sends a write. The server does not know the schema exists. That has practical consequences: - A write through the bare MongoDB driver, a database shell or another service that does not share your models is never cast or validated. - `updateOne()`, `updateMany()` and `findOneAndUpdate()` cast the update but do **not** run validators unless you pass `runValidators: true`. - Documents written before you added a validator are not re-checked until they are saved again. - `unique: true` is not a validator at all: it asks Mongoose to build a unique index, and a duplicate fails at the server with an `E11000` duplicate-key error, not a `ValidationError`. If the database itself must refuse bad documents, that is server-side validation, which the MongoDB material covers; Mongoose's schema is an application-level contract. ## Why teams still rely on it Inside one service the schema earns its keep in several ways: - **One source of truth for shape.** Every handler that writes an order goes through the same casting and validation. - **Readable errors early.** A failed `save()` names each bad path, for example `Path \`total\` (-1) is less than minimum allowed value (0).`, before anything reaches the server. - **Consistent types for reads.** Query filters are cast too, so a hex string from a URL matches a stored `ObjectId` in `find()`. - **Less boilerplate.** Defaults and `timestamps` fill fields that every handler would otherwise set by hand. The trade is that it only protects the code paths that go through it, and a good candidate says so unprompted.

  • In a Mongoose ValidationError, how do you tell a CastError from a ValidatorError?
    Both sit in `err.errors`, keyed by path. A `CastError` means the value could not be converted to the path's SchemaType, such as `'nope'` for an `ObjectId`, and that path's validators then do not run. A `ValidatorError` means the value converted fine but failed a rule; its `kind` names the rule (`required`, `enum`, `min`, or `user defined` for many custom validators).
  • With the timestamps schema option, do you ever set createdAt or updatedAt yourself?
    Normally no. Mongoose sets both on a new document, adds `updatedAt` to the `$set` of updates such as `updateOne()` and `findOneAndUpdate()`, and, on an upsert, puts `createdAt` in `$setOnInsert` so it is only written when the upsert inserts. A write that bypasses Mongoose gets neither field.

  • MongoDB enforces the Mongoose schema, so other writers cannot break it.
  • unique: true is a validator that checks for duplicates before saving.
  • A string sent for a Number path always fails validation.
  • Undeclared keys make save() throw by default.
  • A custom validator runs even when the path is left undefined.
open as a page

What does Mongoose 9's populate() send to MongoDB when a list of Order documents populates its user and product references?

level: middleimportance: must knowfreq 70%

basics

~20 s

populate() runs the main query, then one extra find per populated path and referenced model, with $in over the collected ids, and assigns results in memory: a client-side join with extra round trips that cannot filter parents.

open as a page

Why does a Mongoose 9 pre('save') hook that hashes User passwords leave a password set through findOneAndUpdate() stored in plain text?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Save hooks are document middleware that run for save() and create(); findOneAndUpdate() runs query middleware, where this is the Query and no document exists. Hash in a pre('findOneAndUpdate') hook through getUpdate(), or load the user, assign and save().

open as a page

In Mongoose 9, what does calling lean() on a query give up, and when is it the right choice for a read endpoint?

level: middleimportance: should knowfreq 50%

basics

~20 s

lean() tells Mongoose to skip hydrating results into documents and return plain objects: less memory and CPU, but no change tracking, save(), getters, setters, virtuals (including id), load-time defaults or schema toJSON transforms. Use it for read-only responses.

open as a page

Why can Mongoose 9's findOneAndUpdate() store a value the schema's validators would reject on save(), and what does runValidators change?

level: middleimportance: should knowfreq 60%

basics

~20 s

Update queries never load a document, so Mongoose casts the update but skips validators unless you pass runValidators: true. Even then only the updated paths are checked, this is the Query, and $inc is not validated.

open as a page

Why does a Mongoose 9 Order.aggregate() report match nothing for a user id string from the URL while Order.find() with the same filter works?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Mongoose casts Query filters against the schema but sends Model.aggregate pipelines uncast, so a hex string never equals a stored ObjectId, and a date string never equals a stored Date. Convert values yourself; results come back as plain objects.

open as a page