skip to content

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%

answer

  1. which method fired
  2. document versus query middleware
  3. this is not a document
  4. getUpdate and setUpdate
  5. no next() in Mongoose 9

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().

solid answer

~40 s

Mongoose has document, query, aggregate and model middleware, and each hook name is tied to the methods that trigger it. `pre('save')` fires for `doc.save()` and `Model.create()`; `findOneAndUpdate()`, `updateOne()` and `updateMany()` never build a document, so they run their own query hooks where `this` is the Query. The usual fixes: route password changes through load, assign and `save()`, or add a `pre('findOneAndUpdate')` hook that reads `this.getUpdate()` and writes the hash back with `this.setUpdate()`. In Mongoose 9 every pre hook is written without `next`: use an `async` function. An 8-style `function (next) { ...; next(); }` now fails with `TypeError: next is not a function`, because no callback is passed any more (in `pre('save')` the first argument is the save options). Also remember that validation runs before your `pre('save')` hooks, so `minLength` checks the plain text.

code

javascript · 32 lines
javascript
import { scrypt, randomBytes } from 'node:crypto';
import { promisify } from 'node:util';
import mongoose from 'mongoose';

const scryptAsync = promisify(scrypt);
async function hashPassword(plain) {
  const salt = randomBytes(16).toString('hex');
  const key = await scryptAsync(plain, salt, 64);
  return `${salt}:${key.toString('hex')}`;
}

const userSchema = new mongoose.Schema({
  email: { type: String, required: true },
  password: { type: String, required: true, minLength: 12 }
});

// Document middleware: runs for save() and create(); Mongoose 9 passes no next
userSchema.pre('save', async function () {
  if (!this.isModified('password')) return;
  this.password = await hashPassword(this.password);
});

// Query middleware: `this` is the Query and there is no document
userSchema.pre('findOneAndUpdate', async function () {
  const update = this.getUpdate();
  const plain = update.$set?.password ?? update.password;
  if (plain === undefined) return;
  delete update.password;
  this.setUpdate({ ...update, $set: { ...update.$set, password: await hashPassword(plain) } });
});

export const User = mongoose.model('User', userSchema);

go deeper

for a junior

Recall that pre('save') runs for save() and create(), and that in Mongoose 9 you write it as an async function with no next parameter.

for a middle

Explain document versus query middleware and what this is in each, and name the methods that skip save hooks: the update methods, insertMany and the bare driver.

for a senior

Diagnose the plain-text password from the call site, fix it with load-and-save or a query hook using getUpdate and setUpdate, and catch upgrade breakage from 8-style next() hooks.

for a principal

Decide where write-time invariants live: hooks that every write path must reach, or a service layer that is the only writer. Weigh the hidden coupling hooks add against duplicated logic.

## Four kinds of middleware Mongoose middleware (pre and post **hooks**) are functions registered on a schema with `schema.pre()` and `schema.post()`. Which hook runs depends on the method you call, and each kind binds `this` differently. | Kind | Hook names | Fired by | `this` is | |---|---|---|---| | Document | `validate`, `save`, `init`; `updateOne` / `deleteOne` with `{ document: true, query: false }` | `doc.save()`, `Model.create()`, `doc.validate()` | the document | | Query | `find`, `findOne`, `updateOne`, `updateMany`, `findOneAndUpdate`, `deleteOne`, ... | `exec()`, `then()` or `await` on a Query | the Query | | Aggregate | `aggregate` | `Model.aggregate()` | the Aggregate | | Model | `insertMany`, `bulkWrite`, `createCollection` | those statics | the model | ## Why the password was stored in plain text A password-reset endpoint that calls `User.findOneAndUpdate({ _id }, { password })` sends an update straight to the server. Mongoose never creates a User document for it, so no document hook, `pre('save')` included, has anything to run against. The Mongoose docs say it directly: save hooks are not executed on `findOneAndUpdate()` and the update methods. The same gap exists for: - `updateOne()` and `updateMany()` (query middleware by default); - `insertMany()`, which runs `insertMany` model middleware but does not trigger save middleware; - any write through the bare driver. ## Three ways to fix it 1. **Load, assign, save.** `const user = await User.findById(id); user.password = plain; await user.save();` runs casting, every validator and your `pre('save')` hook. It costs one more round trip, and it is the simplest rule to enforce in review. 2. **Hash in query middleware too.** Register `pre('findOneAndUpdate')` (and `updateOne` if you use it). Inside, `this.getUpdate()` returns the update object; the password may be at the top level or under `$set`. Replace it with the hash and store the result with `this.setUpdate()`. You cannot read the stored document from `this`; if you need it, query for it explicitly. 3. **Document-level `updateOne`.** `schema.pre('updateOne', { document: true, query: false }, fn)` runs for `doc.updateOne()` with `this` as the document, but not for `Model.updateOne()`. Whichever you pick, guard against hashing twice: in `pre('save')`, `if (!this.isModified('password')) return;` skips saves that did not touch the password. ## The Mongoose 9 hook signature Mongoose 9 removed the `next` parameter from pre middleware. A pre hook signals completion by returning (or resolving a promise) and signals failure by throwing (or rejecting): - `schema.pre('save', async function () { ... })` is the standard form. - In a `pre('save')` hook the first argument is now the options passed to `save()`. Legacy code that names it `next` and calls `next()` throws `TypeError: next is not a function`; the save rejects and nothing is written. - The legacy `function (next, done)` form for parallel hooks is gone, as is hooking custom methods and statics that take callbacks. Post hooks are different: a post hook that declares two parameters still receives `next` as its second argument, and error-handling post middleware takes `(error, doc, next)`. ## Choosing between the fixes - **Few write paths, simple rule:** make the service call `save()` for password changes and forbid password fields in update objects; one hook, one place. - **Many update call sites you cannot all change:** add query middleware for each update method you use (`findOneAndUpdate`, `updateOne`, `updateMany`), because each has its own hook name. - **Bulk imports:** `insertMany()` skips save hooks, so hash before building the array or hash in an `insertMany` hook. Whatever you choose, a test that writes through each path and asserts the stored value is not the plain text catches the regression the next time someone adds an update endpoint. ## Ordering details that change the answer - **Validation first.** Validation runs as the first `pre('save')` step, so validators see the value before your hook changes it: a `minLength: 12` on `password` checks the plain text, and nothing validates what the hook writes. With `runValidators: true` on `findOneAndUpdate()`, by contrast, update validators run after your `pre('findOneAndUpdate')` hook and see the hash. - **Register before compiling.** Hooks added after `mongoose.model()` has compiled the schema do not fire. - **Skipping on purpose.** Mongoose 9 accepts a `middleware: false` option, as in `doc.save({ middleware: false })`, that skips user-defined hooks for one call; built-in behaviour such as validation and timestamps still runs.

  • Your Mongoose 9 upgrade makes every save() reject with TypeError: next is not a function. What changed?
    Mongoose 9 no longer passes `next` to pre middleware. A hook written as `function (next) { ...; next(); }` now receives the `save()` options object as its first argument, so calling it throws, the hook fails and the save rejects. Rewrite each pre hook as an `async` function, or one that returns a promise, and throw to signal an error.
  • Why does doc.deleteOne() not fire a pre('deleteOne') hook registered with the defaults?
    By default Mongoose registers `deleteOne` middleware as query middleware, which `Model.deleteOne()` triggers; for legacy reasons `doc.deleteOne()` does not fire it. To hook the document method, register `schema.pre('deleteOne', { document: true, query: false }, fn)`, where `this` is the document being deleted.

  • pre('save') runs for every write, including findOneAndUpdate().
  • Inside pre('findOneAndUpdate'), this is the document being updated.
  • Mongoose 9 pre hooks still receive next() and must call it.
  • insertMany() fires save hooks for each document it inserts.
  • A pre('save') hook runs before validation, so validators see the hash.
  • Hooks added after mongoose.model() still apply to that model.

Assumes Mongoose 9, where pre middleware no longer receives next() and must be async or return a promise; the document versus query middleware split is the same as in Mongoose 8.