Automattic/mongoose · error · MongooseError

AggregationCursor.prototype.close() no longer accepts a…

Error message

AggregationCursor.prototype.close() no longer accepts a callback

What it means

Mongoose 7 removed callback support, mirroring the MongoDB driver. AggregationCursor#close() is now an async method returning a Promise; passing a function as the first argument throws immediately so legacy call sites fail loudly instead of silently never invoking the callback.

Solutions

  1. Replace cursor.close(cb) with await cursor.close() and handle errors with try/catch or .catch()
  2. If a callback API must be kept outward, shim it: cursor.close().then(() => cb(null), cb)
  3. During the Mongoose 7 migration, sweep the codebase for cursor close calls that pass a function

Example fix

// before
aggCursor.close(function (err) {
  if (err) console.error(err);
});

// after
try {
  await aggCursor.close();
} catch (err) {
  console.error(err);
}
Defensive patterns

Strategy: validation

Validate before calling

function closeCursor(cursor, ...args) {
  if (args.some(a => typeof a === 'function')) {
    throw new TypeError('close() takes no callback; await the returned promise');
  }
  return cursor.close();
}

Prevention

When it happens

Trigger: aggCursor.close(() => {}) or aggCursor.close(function (err) {...}) — any function passed as the first argument to close().

Common situations: Upgrading an app from Mongoose 6 or earlier to 7+ without migrating cursor code; copy-pasting pre-2022 tutorials that use the callback style.

Related errors


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

Appendix: source

Thrown at lib/cursor/aggregationCursor.js:240

AggregationCursor.prototype._markError = function(error) {
  this._error = error;
  return this;
};

/**
 * Marks this cursor as closed. Will stop streaming and subsequent calls to
 * `next()` will error.
 *
 * @return {Promise}
 * @api public
 * @method close
 * @emits "close"
 * @see AggregationCursor.close https://mongodb.github.io/node-mongodb-native/7.0/classes/AggregationCursor.html#close
 */

AggregationCursor.prototype.close = async function close() {
  if (typeof arguments[0] === 'function') {
    throw new MongooseError('AggregationCursor.prototype.close() no longer accepts a callback');
  }
  try {
    await this.cursor.close();
  } catch (error) {
    this.listeners('error').length > 0 && this.emit('error', error);
    throw error;
  }
  this.emit('close');
};

/**
 * Marks this cursor as destroyed. Will stop streaming and subsequent calls to
 * `next()` will error.
 *
 * @return {this}
 * @api private
 * @method _destroy
 */

View on GitHub (pinned to 49cdab0136)