Automattic/mongoose · error · MongooseError

Model.ensureIndexes() no longer accepts a callback

Error message

Model.ensureIndexes() no longer accepts a callback

What it means

Model.ensureIndexes() builds all indexes declared in the schema (skipping already-existing ones) and is async-only in Mongoose 7+; a function argument throws right after the context check. Prefer letting `autoIndex`/`Model.init()` handle this and avoid manual calls in production.

Source

Thrown at lib/model.js:1660

 *
 *     const eventSchema = new Schema({ thing: { type: 'string', unique: true } })
 *     const Event = mongoose.model('Event', eventSchema);
 *
 *     Event.on('index', function (err) {
 *       if (err) console.error(err); // error occurred during index creation
 *     });
 *
 * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._
 *
 * @param {object} [options] internal options
 * @return {Promise}
 * @api public
 */

Model.ensureIndexes = async function ensureIndexes(options) {
  _checkContext(this, 'ensureIndexes');
  if (typeof arguments[0] === 'function' || typeof arguments[1] === 'function') {
    throw new MongooseError('Model.ensureIndexes() no longer accepts a callback');
  }

  await new Promise((resolve, reject) => {
    _ensureIndexes(this, options, (err) => {
      if (err != null) {
        return reject(err);
      }
      resolve();
    });
  });
};

/**
 * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](https://mongodb.github.io/node-mongodb-native/7.0/classes/Db.html#createIndex)
 * function.
 *
 * @param {object} [options] internal options
 * @return {Promise}

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Await it: `await User.ensureIndexes();`
  2. Better: rely on connection autoIndex (`await mongoose.connect(uri, { autoIndex: true })`) and drop manual calls
  3. Grep for `ensureIndexes\(` with function arguments during the migration pass

Example fix

// before
User.ensureIndexes(function(err) { if (err) throw err; });

// after
await User.ensureIndexes();
Defensive patterns

Strategy: validation

Validate before calling

const isFn = (a) => typeof a === 'function';
if (isFn(options)) throw new TypeError('ensureIndexes() is promise-only');
await User.ensureIndexes(options);

Prevention

When it happens

Trigger: `User.ensureIndexes(cb)`; `User.ensureIndexes({}, cb)`; startup code following older guides that wire index builds with callbacks.

Common situations: Mongoose major upgrades; codebases where index creation lived in a bootstrap file with callback-based sequencing.

Related errors


AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21). Data as JSON: /api/errors/9f73ae1d42a054d2. Report an issue: GitHub.