Automattic/mongoose · error · MongooseError

Connection.prototype.openUri() no longer accepts a callback

Error message

Connection.prototype.openUri() no longer accepts a callback

What it means

openUri() is the promise-based connection opener behind mongoose.connect() and createConnection(). Mongoose 7 removed callbacks, and _validateArgs (lib/connection.js:1162) throws when the options parameter is a function — the legacy openUri(uri, callback) form. The guard fails fast so the callback is never silently dropped.

Source

Thrown at lib/connection.js:1162

 * @api public
 */

// Treat `on('error')` handlers as handling the initialConnection promise
// to avoid uncaught exceptions when using `on('error')`. See gh-14377.
Connection.prototype.once = function on(event, callback) {
  if (event === 'error' && this.$initialConnection) {
    this.$initialConnection.catch(() => {});
  }
  return EventEmitter.prototype.once.call(this, event, callback);
};

/*!
 * ignore
 */

function _validateArgs(uri, options, callback) {
  if (typeof options === 'function' && callback == null) {
    throw new MongooseError('Connection.prototype.openUri() no longer accepts a callback');
  } else if (typeof callback === 'function') {
    throw new MongooseError('Connection.prototype.openUri() no longer accepts a callback');
  }
}

/*!
 * ignore
 */

function _handleConnectionErrors(err) {
  if (err?.name === 'MongoServerSelectionError') {
    const originalError = err;
    err = new ServerSelectionError();
    err.assimilateError(originalError);
  }

  return err;
}

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Use promises: await mongoose.connect(uri) or await conn.openUri(uri)
  2. Convert (err) => { ... } bodies into try/catch around the awaited call

Example fix

// before
mongoose.connect(uri, (err) => { if (err) return console.error(err); });

// after
try {
  await mongoose.connect(uri);
} catch (err) {
  console.error(err);
}
Defensive patterns

Strategy: validation

Validate before calling

function openUriSafe(uri, ...rest) {
  if (rest.some(a => typeof a === 'function')) {
    throw new TypeError('callback passed to promise-only openUri/connect');
  }
  return conn.openUri(uri, ...rest);
}

Prevention

When it happens

Trigger: conn.openUri('mongodb://...', (err) => { ... }); most commonly mongoose.connect(uri, (err) => { ... }), which forwards to openUri with the function in the options slot (typeof options === 'function' && callback == null).

Common situations: Codebases migrated from mongoose 6 or earlier; legacy tutorials and copied snippets; wrapping connect in callback-style helpers or promise-mux libraries.

Related errors


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