Automattic/mongoose · error · MongooseError

Must call `setClient()` with an instance of MongoClient

Error message

Must call `setClient()` with an instance of MongoClient

What it means

Connection.setClient() adopts an externally managed MongoDB driver MongoClient so Mongoose can run models over it. It strictly checks client instanceof mongodb.MongoClient; passing a Db, a plain object, a string, or a lookalike wrapper fails the instanceof check and throws this MongooseError.

Source

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

    ([namespace, schema]) => ([namespace, schema._buildSchemaMap()])
  ));

  const encryptedFieldsMap = Object.fromEntries(Object.entries(qeMappings).map(
    ([namespace, schema]) => ([namespace, schema._buildEncryptedFields()])
  ));

  return {
    schemaMap, encryptedFieldsMap
  };
};

/*!
 * ignore
 */

NativeConnection.prototype.setClient = function setClient(client) {
  if (!(client instanceof mongodb.MongoClient)) {
    throw new MongooseError('Must call `setClient()` with an instance of MongoClient');
  }
  if (this.readyState !== STATES.disconnected) {
    throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.');
  }
  if (client.topology == null) {
    throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.');
  }

  this._connectionString = client.s.url;
  _setClient(this, client, {}, client.s.options.dbName);

  for (const model of Object.values(this.models)) {
    // Errors handled internally, so safe to ignore error
    model.init().catch(function $modelInitNoop() {});
  }

  return this;
};

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Pass the MongoClient instance itself: await conn.setClient(client).
  2. If you hold a Db, reach its client with db.client (driver >= 4) and pass that.
  3. For wrapped clients, keep the raw instance reference for setClient and attach the wrapper elsewhere.
  4. In tests, use a real client or mongodb-memory-server rather than a stub, so instanceof holds.

Example fix

// before
const db = client.db('shop');
await conn.setClient(db); // Db is not a MongoClient

// after
await conn.setClient(client); // pass the client; dbName comes from client options
Defensive patterns

Strategy: type-guard

Validate before calling

import { MongoClient } from 'mongodb';
if (!(client instanceof MongoClient)) {
  throw new TypeError('expected a mongodb.MongoClient instance');
}
await conn.setClient(client);

Type guard

import { MongoClient } from 'mongodb';
function isMongoClient(v) {
  return v instanceof MongoClient;
}

Prevention

When it happens

Trigger: conn.setClient(client.db('mydb')) (a Db, not a client); setClient({ ...client }) or a custom wrapper class; mocks/stubs in unit tests that are not actual MongoClient instances.

Common situations: Migrating code that stored Db handles from older driver versions; passing a proxied client from an APM/instrumentation layer that breaks instanceof; test doubles replacing the driver.

Related errors


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