
Mongoose Next Is Not a Function - Stop Calling next() in v9
Skilldham
Engineering deep-dives for developers who want real understanding.
Last updated: November 2026
TL;DR
Seeing mongoose next is not a function after an upgrade? Mongoose 9 removed next() from pre hooks.
The fix is short. Drop the next parameter and make the hook async. Use return to skip work and throw to report errors.
Remove next from every schema.pre() callback
Replace next(err) with throw err
Check your Mongoose plugins too, because they break the same way
You upgrade to Mongoose 9. You start the server. You sign up a test user.
The request crashes.
bash
TypeError: next is not a functionThe stack trace points at your pre('save') hook. It is the same hook that worked for years.
Every tutorial still writes it this way. Most AI assistants do too.
So you check bcrypt. You check your imports. You delete node_modules and reinstall.
Nothing helps, because your hook is not wrong for Mongoose 8. It is wrong for Mongoose 9. Here is exactly what changed, and the rewrite for every hook pattern that breaks.
Why You Get Mongoose Next Is Not a Function
This error has one root cause. Your code still uses the old callback style. Mongoose stopped supporting it.
What Changed in Mongoose 9.0
Mongoose 9.0.0 shipped on 21 November 2025. Its changelog lists a breaking change that hits almost every project. Callback-based pre middleware is gone.
Before version 9, Mongoose passed a next callback into every pre hook. Calling it told Mongoose to keep going. Mongoose 5 added promise support but kept next for old code.
Mongoose 9 removed it for good. The hook runner is a small library called kareem. Version 3 of kareem treats every pre hook as promise-based.
It waits for your function to return. If it returns a promise, it waits for that to settle. It never hands you a callback.
Why Your Code Calls Something That Is Not a Function
Your hook still declares function (next). JavaScript does not care what you name a parameter. Whatever Mongoose passes in that first slot lands in next.
In Mongoose 9, that value is not a callback. So the moment your code runs next(), JavaScript throws. That is the full story behind the mongoose next is not a function crash.
The Smallest Broken Hook
Here is the simplest version of the problem. It sets a timestamp and nothing else.
javascript
// Wrong: callback-style pre hook, crashes on Mongoose 9
userSchema.pre("save", function (next) {
this.lastSavedAt = new Date();
next();
});The assignment runs fine. The crash happens on the next() line. Your save() call rejects with the TypeError.
javascript
// Correct: no next parameter, Mongoose 9 moves on when the function returns
userSchema.pre("save", function setLastSavedAt() {
this.lastSavedAt = new Date();
});There is no async work here, so a plain function is enough. Mongoose runs it and moves on when it returns.
Name the function, too. The name shows up in stack traces, which makes the next bug easier to find.

Fix 1: Password Hashing in pre(‘save’)
This is the hook that breaks most often. Almost every auth tutorial from the last ten years uses it. AI tools still generate it by default.
The Pattern Every Tutorial Teaches
javascript
// Wrong: the classic tutorial hook, broken on Mongoose 9
import bcrypt from "bcrypt";
userSchema.pre("save", function (next) {
if (!this.isModified("password")) return next();
bcrypt.hash(this.password, 12, (err, hash) => {
if (err) return next(err);
this.password = hash;
next();
});
});This hook fails in two different ways. When the password did not change, return next() throws right away. Profile updates start failing.
The second failure is worse. When the password did change, the hash runs inside a callback. Mongoose 9 does not wait for callbacks.
Your function returns undefined straight away. Mongoose treats the hook as done and keeps saving. The save can finish before bcrypt does.
The Async Rewrite
javascript
// Correct: async hook with the bcrypt promise API (Mongoose 9)
import bcrypt from "bcrypt";
userSchema.pre("save", async function hashPassword() {
if (!this.isModified("password")) return;
this.password = await bcrypt.hash(this.password, 12);
});The async function returns a promise. Mongoose waits for that promise before it writes anything. The hash is always in place before the save.
Why the Early Return Still Works
A bare return inside an async function resolves its promise. Mongoose reads that as a finished hook. So return does the job that return next() used to do.
this.isModified() still works the same way. It is a document method, and Mongoose 9 did not touch it.
Keep the function keyword, though. An arrow function has no this, so this.isModified would fail.
Do Not Half-Migrate
Some developers add async and stop there. That does not fix anything.
javascript
// Wrong: async alone does not help if next() is still called
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 12);
next();
});Both next() calls still throw. The async keyword only changes how the error surfaces. Remove the parameter and every call to it.
If you migrated to Mongoose 9 and logins look odd, check recent users. Look for passwords that do not start with $2. Those were saved before the hash finished.
Fix 2: Query Hooks Like pre(‘findOneAndUpdate’)
Save hooks do not run on findOneAndUpdate(). So many projects add a query hook to hash passwords there too. That hook breaks the same way.
The Broken Query Hook
javascript
// Wrong: callback-style query hook, crashes on Mongoose 9
userSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if (!update.password) return next();
bcrypt.hash(update.password, 12, (err, hash) => {
if (err) return next(err);
update.password = hash;
next();
});
});Inside a query hook, this is the Query. It is not a document. That part did not change in Mongoose 9.
The callback part did change. So this hook hits the same two failures as the save hook.
The Async Rewrite
javascript
// Correct: async query hook that handles both update shapes (Mongoose 9)
import bcrypt from "bcrypt";
userSchema.pre("findOneAndUpdate", async function hashPasswordOnUpdate() {
const update = this.getUpdate();
if (!update) return;
const plain = update.$set?.password ?? update.password;
if (!plain) return;
const hash = await bcrypt.hash(plain, 12);
if (update.$set?.password) {
update.$set.password = hash;
} else {
update.password = hash;
}
this.setUpdate(update);
});Reading and Writing the Update Object
getUpdate() returns the update you passed to the query. Callers write it in two shapes. Some pass { password } and some pass { $set: { password } }.
The old hook only checked the first shape. The rewrite checks both. setUpdate() then writes the hashed version back onto the query.
Is TypeScript complaining about this in query hooks? The same typing gotchas show up in the Mongoose populate TypeScript error.
Fix 3: pre(‘deleteOne’) on Subdocuments
Cleanup hooks are the third common pattern. They delete related data when a document or subdocument goes away.
Document Middleware vs Query Middleware
By default, deleteOne hooks are query middleware. That means this is a Query, not the document. To get the document, pass { document: true, query: false }.
That option still works in Mongoose 9. Only the callback style is gone.
The Broken Cleanup Hook
javascript
// Wrong: cleanup hook that chains next() onto a promise
const commentSchema = new mongoose.Schema({
text: String,
authorId: mongoose.Schema.Types.ObjectId,
});
commentSchema.pre("deleteOne", { document: true, query: false }, function (next) {
Attachment.deleteMany({ commentId: this._id })
.then(() => next())
.catch(next);
});This one is sneaky. The .then(() => next()) throws inside the promise chain. Then .catch(next) runs and calls next again.
That second call throws too. Nothing catches it, so you get an unhandled rejection. Meanwhile, Mongoose already moved on and deleted the comment.
Cascade Cleanup Without next
javascript
// Correct: async document hook, Mongoose 9 waits for the cleanup
const commentSchema = new mongoose.Schema({
text: String,
authorId: mongoose.Schema.Types.ObjectId,
});
commentSchema.pre(
"deleteOne",
{ document: true, query: false },
async function removeAttachments() {
await Attachment.deleteMany({ commentId: this._id });
}
);Now Mongoose waits for deleteMany to finish. If it fails, the error rejects the delete. You no longer get orphaned attachments.
Fix 4: Replace next(err) With throw
Many hooks use next(err) for validation. That pattern is also gone in Mongoose 9.
The Old Way to Report Errors
javascript
// Wrong: next(err) for validation, crashes on Mongoose 9
orderSchema.pre("save", function (next) {
if (this.total < 0) {
return next(new Error("Order total cannot be negative"));
}
next();
});This crashes with the TypeError instead of your error. Your API returns a confusing 500. The real message never reaches the client.
Throw Instead
javascript
// Correct: throw to reject the save (Mongoose 9)
orderSchema.pre("save", function validateTotal() {
if (this.total < 0) {
throw new Error("Order total cannot be negative");
}
});A thrown error rejects the save() promise. Your route handler catches it like any other error. Inside an async hook, throw works the same way.
Errors After next() Are No Longer Ignored
There is a second, quieter change. In Mongoose 8, an error thrown after next() got ignored. The save still succeeded.
Mongoose 9 gives thrown errors priority. So old hooks with hidden bugs may now fail loudly. That is good, but expect a few surprise errors after the upgrade.
Mongoose 9 also stopped letting next(null, arg) overwrite the options passed to save(). If a hook relied on that trick, rewrite it.
The official Mongoose 9 migration guide covers these changes. Maintainers expanded the next() section in 9.0.1 after issue #15813 flagged the gap.
How to Find Broken Mongoose Plugins in node_modules
Fixing your own hooks is not enough. Plugins add their own pre hooks. Many of them still use callbacks.
Search Your Own Code First
bash
# Find callback-style pre hooks in your own source
grep -rnE "\.pre\(.*function ?\((next|done|cb)" src/
# Also catch hooks written over multiple lines
grep -rnE "function ?\((next|done|cb)\)" src/models/The first command finds one-line hook definitions. The second finds functions whose only parameter is next, done, or cb. Review each match by hand.
Search Installed Plugins
bash
# Find callback-style hooks inside Mongoose plugins
grep -rn "function (next" node_modules/mongoose-*
# Wider search that also catches cb, done, and missing spaces
grep -rnE "function ?\((next|cb|done)" node_modules/mongoose-* --include=*.jsAny match in a plugin means that plugin will likely crash on Mongoose 9. Check its GitHub issues before you upgrade.
mongoose-encryption: cb is not a function
mongoose-encryption fails with a different message: TypeError: cb is not a function. Same cause, different parameter name. Issue #130 was opened on 30 September 2026.
At the time of writing, that issue is still open.
You have three options. Stay on Mongoose 8 for now, or patch the plugin. The long-term option is MongoDB’s built-in Client-Side Field Level Encryption.
mongoose-sequence and Other Plugins
mongoose-sequence users hit the same next is not a function crash. Check the plugin’s latest release notes for Mongoose 9 support.
If no fixed release exists, patch it yourself. The rewrite is the same: drop next, return a promise.
Patch a Plugin With patch-package
bash
# 1. Install patch-package
npm install --save-dev patch-package
# 2. Edit the plugin file in node_modules
# Rewrite each function (next) hook as an async function
# 3. Save your edit as a patch file
npx patch-package mongoose-sequencejson
{
"scripts": {
"postinstall": "patch-package"
}
}The patch lives in a patches/ folder in your repo. It reapplies after every npm install. Remove it once the plugin ships a fix.
If you need to pin Mongoose 8 for a while, lock it in package.json. Commit your lockfile too. To verify what actually installed, see how to check your npm lockfile after a supply chain attack.
The Silent Failure That Hides This Crash
Sometimes there is no crash at all. The app keeps running, but something important quietly stops working. This is the most dangerous version of the bug.
How a Fallback Swallows the Error
In tenali issue #295, auth silently fell back to an in-memory store. The startup code caught every error and switched stores. The hook crash looked like a database outage.
javascript
// Wrong: one catch block hides the hook crash
let userStore;
try {
await mongoose.connect(process.env.MONGODB_URI);
await User.create({ email: "admin@example.com", password: process.env.ADMIN_PASSWORD });
userStore = "mongo";
} catch (err) {
console.log("MongoDB unavailable, using memory store");
userStore = "memory";
}User.create() runs the save hook. The hook throws next is not a function. The catch block logs a misleading message and keeps going.
Users can sign up. Their data vanishes on restart. Nobody sees the real error.
Fail Loud on Startup
javascript
// Correct: separate connect errors from seed errors, never hide either
async function start() {
await mongoose.connect(process.env.MONGODB_URI);
const existing = await User.findOne({ email: "admin@example.com" });
if (!existing) {
await User.create({ email: "admin@example.com", password: process.env.ADMIN_PASSWORD });
}
}
start().catch((err) => {
console.error("Startup failed:", err);
process.exit(1);
});Now a hook bug stops the process with the real stack trace. Your logs show the TypeError, not a fake outage. Your deploy fails before users see anything.
If the connect step itself hangs instead, that is a different problem. Our post on Mongoose buffering timed out in production covers that case.
Add a Hook Smoke Test
javascript
// Correct: test that the save hook really hashes on Mongoose 9
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
import { User } from "../src/models/User.js";
let mongo;
before(async () => {
mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
});
after(async () => {
await mongoose.disconnect();
await mongo.stop();
});
test("pre save hook hashes the password", async () => {
const user = await User.create({ email: "test@example.com", password: "plain-text-123" });
assert.notEqual(user.password, "plain-text-123");
assert.ok(user.password.startsWith("$2"));
});Run it with node --test. This test fails on the old callback hook and passes on the async rewrite.
Keep it in CI. Then the next upgrade cannot break auth silently.
Key Takeaways
The mongoose next is not a function error means Mongoose 9 removed next() from pre hooks.
Mongoose 9.0.0 shipped on 21 November 2025 with this breaking change.
Remove the next parameter, then use async when the hook awaits anything.
Use return to skip a hook and throw to reject the operation.
Callback-based bcrypt hashing can let a save finish before the hash does.
Grep node_modules/mongoose-* for function (next before upgrading.
Never let a catch-all hide startup errors. Fail loud and exit.
Keep a smoke test that saves a real document through your hooks.
FAQ
Why does Mongoose say next is not a function?
Your pre hook still calls next(). Mongoose 9 no longer passes a callback into pre hooks. Remove the parameter and return a promise instead.
Which Mongoose version removed next() from pre hooks?
Mongoose 9.0.0, released on 21 November 2025. Mongoose 8 still accepts both styles. The async style works on both, so migrate before you upgrade.
Can I still use a plain function without async?
Yes. If the hook does no async work, a plain function is fine. Mongoose 9 moves on as soon as it returns.
How do I pass an error from a pre hook in Mongoose 9?
Throw it. In a plain function, throw rejects the operation. In an async function, a thrown error or rejected promise does the same.
Does this.isModified still work in Mongoose 9?
Yes. this.isModified() is a document method and did not change. Just keep the function keyword, because arrow functions have no this.
Why does my plugin throw cb is not a function?
The plugin uses a callback-style hook and named the parameter cb. mongoose-encryption fails this way. Patch the plugin, wait for a fix, or stay on Mongoose 8.
Should I downgrade to Mongoose 8 to fix this?
Only as a short-term fix while a plugin catches up. Rewriting your hooks is quick. The async style also works on Mongoose 8, so you can migrate first.
Can I use an arrow function for a Mongoose hook?
No. Arrow functions do not get their own this. Your hook needs this to reach the document or the query.
Final Word
Mongoose 9 did not break your hooks at random. It finished a move to promises that started back in Mongoose 5. Once you see that, every fix follows one rule: no next, just return or throw.
That rule matters most in auth code. A broken hook there can save bad data or hide behind a fallback. Test it.
If you run MongoDB on serverless, read our guide to MongoDB attachDatabasePool on Vercel next.
Want fixes like this before they hit your build? Subscribe to the SkillDham newsletter for real-world dev fixes.