Why can Mongoose 9's findOneAndUpdate() store a value the schema's validators would reject on save(), and what does runValidators change?
answer
- documents versus queries
- casting still happens
- off unless you opt in
- only the updated paths
- $inc slips past
basics
~20 sUpdate 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.
solid answer
~40 sValidation is document middleware: it runs as the first `pre('save')` step. `updateOne()`, `updateMany()` and `findOneAndUpdate()` send an update without building a document, so by default Mongoose only **casts** it: `{ total: 'abc' }` still throws a `CastError`, but `{ status: 'lost' }` against an `enum` is written. Passing `runValidators: true` (per query, or globally with `mongoose.set('runValidators', true)`) turns on **update validators**, with caveats: they check only paths named in the update, `required` fails only when you `$unset` the path, they run for `$set`, `$unset`, `$push`, `$addToSet`, `$pull` and `$pullAll` but not `$inc`, and inside a custom validator `this` is the Query, so you read other fields with `this.get()`. When an invariant spans several fields, load the document, change it and `save()`.
code
javascript · 20 linesconst orderSchema = new mongoose.Schema({
status: { type: String, enum: ['pending', 'paid', 'shipped'], required: true },
total: { type: Number, min: 0 }
});
const Order = mongoose.model('Order', orderSchema);
// Written: update validators are off by default
await Order.updateOne({ _id: id }, { status: 'lost' });
// Rejected with a ValidationError: `lost` is not a valid enum value
await Order.updateOne({ _id: id }, { status: 'lost' }, { runValidators: true });
// Rejected with a CastError even without runValidators: casting always runs
await Order.updateOne({ _id: id }, { total: 'abc' });
// Written despite min: 0, because update validators ignore $inc
await Order.updateOne({ _id: id }, { $inc: { total: -500 } }, { runValidators: true });
// Rejected: required only fails on an explicit $unset
await Order.updateOne({ _id: id }, { $unset: { status: 1 } }, { runValidators: true });go deeper
Remember the one-line rule: save() validates, update queries do not unless you pass runValidators: true. Casting still happens either way.
Explain why: validation is a pre-save document step and updates have no document. List the caveats of update validators: updated paths only, required only on $unset, the operator list, and this as the Query.
Spot the production leaks: an $inc taking a balance below min, a cross-field rule that sees only the update, hooks that never fire. Choose load-and-save when a rule needs the stored document.
Decide a team default, such as global runValidators plus a convention for which writes must go through save(), and make sure request bodies are whitelisted before they become update objects.
## Two different code paths Mongoose writes data in two very different ways, and validation only follows one of them by default. | | `doc.save()` / `Model.create()` | `updateOne()` / `updateMany()` / `findOneAndUpdate()` | |---|---|---| | What Mongoose holds | a full document in memory | a filter and an update object | | Casting | yes, every path | yes, the filter and the update | | Validators | yes, as the first `pre('save')` step | only with `runValidators: true` | | `pre('save')` hooks | yes | no, query middleware instead | | `this` in a custom validator | the document | the Query | A **validator** is a rule declared on a schema path (`required`, `enum`, `min`, `match`, or your own `validate` function). **Casting** is the separate step that converts a value to the path's type. On the update path Mongoose still casts, which is why `Order.updateOne({ _id }, { total: 'abc' })` fails with `Cast to Number failed for value "abc"`. What it does not do is ask whether the converted value is allowed, so `{ status: 'lost' }` reaches the collection even though the schema's `enum` only lists `pending`, `paid` and `shipped`. ## Turning update validators on The option is `runValidators`. You can set it: 1. per call: `Order.findOneAndUpdate(filter, update, { runValidators: true })`; 2. globally, before models run queries: `mongoose.set('runValidators', true)`, whose default is `false`. With it on, Mongoose validates the casted update before sending it and rejects with a `ValidationError`, the same error class `save()` produces. ## The caveats that surprise people Update validators are deliberately narrower than document validation, and the Mongoose docs keep them off by default because they have several caveats. The ones that surprise people: - **Only updated paths are checked.** A `required` path that the update does not mention is not checked at all; `required` fails only when the update explicitly `$unset`s it. - **Only some operators are validated:** `$set`, `$unset`, `$push`, `$addToSet`, `$pull` and `$pullAll`. An `$inc` that takes `total` below its `min: 0` is not validated. - **Array operators validate the elements, not the array.** A validator on the array itself, such as a maximum length, does not run for `$push` or `$addToSet`. - **`this` is the Query, not a document.** A custom validator that compares two fields must read the other one with `this.get('field')`, and it only sees what the update sets, not what is stored. - **No save hooks.** Logic you put in `pre('save')`, such as hashing or derived fields, does not run for these calls either. ## When to load and save instead If a rule depends on the stored document, such as "a shipped order cannot drop back to pending", update validators cannot see the old value. The reliable pattern is: 1. load the document with `findById()`; 2. change the fields; 3. call `save()`, which casts, runs every validator with `this` as the document, and fires your hooks. That costs an extra round trip and is not atomic with respect to a concurrent writer, so use a targeted update with `runValidators` when the rule is per-field, and load-and-save when it is about the whole document. ## Reading the options together In Mongoose 9 the usual call for an edit endpoint looks like `Order.findOneAndUpdate({ _id: id }, { $set: changes }, { runValidators: true, returnDocument: 'after' })`. The update is cast, the paths in `changes` are validated, the `timestamps` option (if the schema enables it) adds `updatedAt`, and you get the document as it is after the update. If `changes` came straight from a request body, remember that `strict` (on by default) drops undeclared keys from the update, but it does not stop a client from setting a declared field it should not touch; whitelist the fields you accept. ## A checklist for an edit endpoint - Pick the fields you accept from the request and build `$set` from them, never from the raw body. - Pass `runValidators: true`, or set it globally once, so `enum`, `min` and `match` apply to edits as they do to creates. - Use `$set` rather than `$inc` for values that have a `min` or `max`, or check the bound in the filter itself. - Move rules that compare the new value with the stored one into a load-and-save path. - Remember that `pre('save')` logic is skipped here; if a field needs hashing or deriving on every write, add matching query middleware or route the write through `save()`.
- Inside a Mongoose custom validator, how do you compare two fields when it runs as an update validator?Under update validators `this` is the Query, so `this.name` is meaningless; call `this.get('name')` to read the value the update sets. It returns nothing for a field the update does not touch, because Mongoose never loads the stored document. If the rule needs stored values, load the document and `save()` instead.
- Should a team set mongoose.set('runValidators', true) globally?It is a reasonable default: it removes the most common surprise, an `enum` or `min` silently ignored on edits. Developers still need to know its limits: `$inc` and array-level validators are skipped, unmentioned `required` paths pass, and cross-field rules see only the update. It complements load-and-save for whole-document invariants rather than replacing it.
- updateOne() runs the same validators as save() by default.
- Without runValidators, Mongoose sends the update values uncast.
- runValidators checks every required path, even ones the update omits.
- A custom update validator can read the stored document through this.
- With runValidators on, $inc is checked against min and max.
- findOneAndUpdate() fires pre('save') hooks, so validation happens there.