Mongoose Stopped Accepting Callbacks for Some of Its Functions

Matthew C.
jump to solution

The Problem

When using Mongoose, which is a Node.js library for MongoDB object modeling, you may encounter an error similar to the following:

MongooseError: Model.prototype.save() no longer accepts a callback

This error occurs when passing a callback as an argument to certain Mongoose methods in Mongoose version 7+.

For example, before version 7, the Model.save() method could be called with an optional callback function as an argument to handle an error:

product.save(function(err) {
  // ...
});

But from version 7, using a callback as an argument in the save() method returns undefined, because the method can no longer accept callback arguments and instead returns a promise.

The Solution

You can avoid using callbacks by using the async/await syntax in an asynchronous function:

try {
  await product.save();
} catch (err) {
  // ...
}

Using async/await with Mongoose improves code readability when executing multiple async Mongoose methods in sequence. This prevents callback hell, which is when you have multiple levels of callbacks within callbacks.

To convert your Mongoose methods to use async/await syntax, you can use the free tool, Convert Callbacks to Async/Await with OpenAI, built by the maintainer of the Mongoose library.

Async/await is supported in Node.js version 8+. You can also have a top-level await from Node.js v14.8.0.

If your Node.js version doesn’t support async functions, use a promise instead:

product.save()
  .then(function() {
    // Product saved successfully
  })
  .catch(function(err) {
    // Handle the error
  });

Note

You can find a full list of the methods that no longer accept callbacks in the Mongoose docs, including the following methods:

  • Connection.prototype.startSession
  • Model.find
  • Model.create
  • Model.bulkWrite
  • Model.prototype.save
  • Query.prototype.findOneAndUpdate

Best Practice

If you are migrating to a new Mongoose version, it’s best to migrate incrementally from version to version, as each upgrade has several backward-breaking changes. Here are the migration guides:

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry