With Mongoose 9, what does a schema add on top of a MongoDB collection, and where is that schema actually enforced?
answer
- who checks the shape
- cast before validate
- CastError versus ValidatorError
- strict mode and undeclared keys
- model class, document instance
basics
~20 sA 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 sA 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 linesconst 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
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.
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.
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.
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.