{"record":{"id":"54cb4b1c2430a2c6","repo":"Automattic/mongoose","slug":"cannot-call-setclient-on-a-connection-that-is","errorCode":null,"errorMessage":"Cannot call `setClient()` on a connection that is already connected.","messagePattern":"Cannot call `setClient\\(\\)` on a connection that is already connected\\.","errorType":"exception","errorClass":"MongooseError","httpStatus":null,"severity":"error","filePath":"lib/drivers/node-mongodb-native/connection.js","lineNumber":415,"sourceCode":"  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};\n\n/*!\n * ignore","sourceCodeStart":397,"sourceCodeEnd":433,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/drivers/node-mongodb-native/connection.js#L397-L433","documentation":"setClient() may only attach an external MongoClient while the connection is in the disconnected state. If the connection is currently connecting or connected (e.g. after mongoose.connect() or a prior openUri()), setClient throws this MongooseError because the connection is already bound to another client/topology.","triggerScenarios":"await mongoose.connect(uri); await mongoose.connection.setClient(client); - also calling setClient after openUri(), or calling setClient twice without closing in between.","commonSituations":"Bootstrap code that both connects by URI and then tries to hand over a pre-built client; runtime switch-database features implemented via setClient on the live default connection.","solutions":["Close first: await mongoose.connection.close(); await mongoose.connection.setClient(client);.","Pick one connection strategy at startup: URI-based connect() OR client-based setClient(), never both.","For multiple clients, use separate connections: const c2 = mongoose.createConnection(); await c2.setClient(client2);."],"exampleFix":"// before\nawait mongoose.connect(uri);\nawait mongoose.connection.setClient(client); // throws: already connected\n\n// after\nawait mongoose.connection.close();\nawait mongoose.connection.setClient(client);","handlingStrategy":"validation","validationCode":"async function attachClient(conn, client) {\n  if (conn.readyState !== 0) { // 0 === STATES.disconnected\n    await conn.close();\n  }\n  return conn.setClient(client);\n}","typeGuard":"function isDisconnected(conn) {\n  return conn.readyState === 0; // STATES.disconnected\n}","tryCatchPattern":null,"preventionTips":["Encapsulate 'connect by URI' vs 'adopt client' in one bootstrap function with mutually exclusive branches.","Check connection.readyState before lifecycle-sensitive calls like setClient().","Never call setClient on the shared default connection while requests are in flight; close() drains in-flight operations first."],"tags":["mongoose","setclient","connection-state","lifecycle"],"backgroundTag":"connection-already-open","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}