{"record":{"id":"89cc9b5908e41fd9","repo":"Automattic/mongoose","slug":"must-call-setclient-with-an-instance-of-mongoc","errorCode":null,"errorMessage":"Must call `setClient()` with an instance of MongoClient","messagePattern":"Must call `setClient\\(\\)` with an instance of MongoClient","errorType":"exception","errorClass":"MongooseError","httpStatus":null,"severity":"error","filePath":"lib/drivers/node-mongodb-native/connection.js","lineNumber":412,"sourceCode":"    ([namespace, schema]) => ([namespace, schema._buildSchemaMap()])\n  ));\n\n  const encryptedFieldsMap = Object.fromEntries(Object.entries(qeMappings).map(\n    ([namespace, schema]) => ([namespace, schema._buildEncryptedFields()])\n  ));\n\n  return {\n    schemaMap, encryptedFieldsMap\n  };\n};\n\n/*!\n * ignore\n */\n\nNativeConnection.prototype.setClient = function setClient(client) {\n  if (!(client instanceof mongodb.MongoClient)) {\n    throw new MongooseError('Must call `setClient()` with an instance of MongoClient');\n  }\n  if (this.readyState !== STATES.disconnected) {\n    throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.');\n  }\n  if (client.topology == null) {\n    throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.');\n  }\n\n  this._connectionString = client.s.url;\n  _setClient(this, client, {}, client.s.options.dbName);\n\n  for (const model of Object.values(this.models)) {\n    // Errors handled internally, so safe to ignore error\n    model.init().catch(function $modelInitNoop() {});\n  }\n\n  return this;\n};","sourceCodeStart":394,"sourceCodeEnd":430,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/drivers/node-mongodb-native/connection.js#L394-L430","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Pass the MongoClient instance itself: await conn.setClient(client).","If you hold a Db, reach its client with db.client (driver >= 4) and pass that.","For wrapped clients, keep the raw instance reference for setClient and attach the wrapper elsewhere.","In tests, use a real client or mongodb-memory-server rather than a stub, so instanceof holds."],"exampleFix":"// before\nconst db = client.db('shop');\nawait conn.setClient(db); // Db is not a MongoClient\n\n// after\nawait conn.setClient(client); // pass the client; dbName comes from client options","handlingStrategy":"type-guard","validationCode":"import { MongoClient } from 'mongodb';\nif (!(client instanceof MongoClient)) {\n  throw new TypeError('expected a mongodb.MongoClient instance');\n}\nawait conn.setClient(client);","typeGuard":"import { MongoClient } from 'mongodb';\nfunction isMongoClient(v) {\n  return v instanceof MongoClient;\n}","tryCatchPattern":null,"preventionTips":["Type the parameter as MongoClient (TypeScript) so the compiler catches Db/object mix-ups.","Store and pass MongoClient handles, not Db handles, through your DI container.","With proxy-based instrumentation, keep the raw client instance for setClient."],"tags":["mongoose","setclient","mongodb-driver","instanceof","type-check"],"backgroundTag":"invalid-driver-object","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}