Automattic/mongoose · error · MongooseError

Cannot modify Mongoose driver if a connection is already ope

Error message

Cannot modify Mongoose driver if a connection is already open. Call `mongoose.disconnect()` before modifying the driver

What it means

Error "Cannot modify Mongoose driver if a connection is already open. Call `mongoose.disconnect()` before modifying the driver" thrown in Automattic/mongoose.

Source

Thrown at lib/mongoose.js:170

 * Mongoose-specific interface that defines functions like `find()`.
 *
 * @memberOf Mongoose
 * @method setDriver
 * @api public
 */

Mongoose.prototype.setDriver = function setDriver(driver) {
  const _mongoose = this instanceof Mongoose ? this : mongoose;

  if (_mongoose.__driver === driver) {
    return _mongoose;
  }

  const openConnection = _mongoose.connections && _mongoose.connections.find(conn => conn.readyState !== STATES.disconnected);
  if (openConnection) {
    const msg = 'Cannot modify Mongoose driver if a connection is already open. ' +
      'Call `mongoose.disconnect()` before modifying the driver';
    throw new MongooseError(msg);
  }
  _mongoose.__driver = driver;

  if (Array.isArray(driver.plugins)) {
    for (const plugin of driver.plugins) {
      if (typeof plugin === 'function') {
        _mongoose.plugin(plugin);
      }
    }
  }

  if (driver.SchemaTypes != null) {
    Object.assign(mongoose.Schema.Types, driver.SchemaTypes);
  }

  const Connection = driver.Connection;
  const oldDefaultConnection = _mongoose.connections[0];
  _mongoose.connections = [new Connection(_mongoose)];

View on GitHub (pinned to 49cdab0136)

When it happens

Trigger: Thrown at lib/mongoose.js:170 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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