Automattic/mongoose · error · MongooseError

Can't call `openUri()` on an active connection with differen

Error message

Can't call `openUri()` on an active connection with different connection strings. Make sure you aren't calling `mongoose.connect()` multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections

What it means

While a connection is in the connecting or connected state, calling openUri()/connect() on it again with a different connection string throws this MongooseError. A connection object is bound to one URI for its lifetime; silently switching URIs would orphan driver pools and model bindings, so Mongoose refuses.

Source

Thrown at lib/drivers/node-mongodb-native/connection.js:248

 */

NativeConnection.prototype.createClient = async function createClient(uri, options) {
  if (typeof uri !== 'string') {
    throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
      `string, got "${typeof uri}". Make sure the first parameter to ` +
      '`mongoose.connect()` or `mongoose.createConnection()` is a string.');
  }

  if (this._destroyCalled) {
    throw new MongooseError(
      'Connection has been closed and destroyed, and cannot be used for re-opening the connection. ' +
      'Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`.'
    );
  }

  if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {
    if (this._connectionString !== uri) {
      throw new MongooseError('Can\'t call `openUri()` on an active connection with ' +
        'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' +
        'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections');
    }
  }

  options = processConnectionOptions(uri, options);

  if (options) {

    const autoIndex = options.config?.autoIndex ?? options.autoIndex;
    if (autoIndex != null) {
      this.config.autoIndex = autoIndex !== false;
      delete options.config;
      delete options.autoIndex;
    }

    if ('autoCreate' in options) {
      this.config.autoCreate = !!options.autoCreate;

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Disconnect first: await mongoose.disconnect(); await mongoose.connect(uriB);.
  2. For concurrent databases, use separate connections: const connB = mongoose.createConnection(uriB) instead of switching the default.
  3. Make bootstrap idempotent: connect once, cache the promise, never call connect() per request or per module reload.

Example fix

// before
await mongoose.connect(process.env.MONGO_URI_A);
// later, same process:
await mongoose.connect(process.env.MONGO_URI_B); // throws

// after
await mongoose.disconnect();
await mongoose.connect(process.env.MONGO_URI_B);
// or keep both alive:
const connB = await mongoose.createConnection(process.env.MONGO_URI_B).asPromise();
Defensive patterns

Strategy: fallback

Validate before calling

let connectedUri = null;
async function connectOnce(uri) {
  if (connectedUri === uri && mongoose.connection.readyState === 1) {
    return mongoose.connection.asPromise();
  }
  if (mongoose.connection.readyState !== 0) {
    await mongoose.disconnect();
  }
  const conn = await mongoose.connect(uri);
  connectedUri = uri;
  return conn;
}

Try / catch

try {
  await mongoose.connect(uri);
} catch (err) {
  if (err instanceof mongoose.MongooseError && err.message.includes('different connection strings')) {
    await mongoose.disconnect();
    return mongoose.connect(uri); // retry once on a clean connection
  }
  throw err;
}

Prevention

When it happens

Trigger: await mongoose.connect(uriA) then later await mongoose.connect(uriB) in the same process (different string, including different dbName or options embedded in the URI); HMR/dev-mode reloads re-running bootstrap with a different env; sequential tests pointing at different databases.

Common situations: Test suites switching between dev/test databases without disconnecting; runtime switch-database features implemented by reconnecting the default connection; hot module replacement re-executing connect code.

Related errors


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