{"record":{"id":"65bb467a62da0d3b","repo":"Automattic/mongoose","slug":"can-t-call-openuri-on-an-active-connection-wit","errorCode":null,"errorMessage":"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","messagePattern":"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","errorType":"exception","errorClass":"MongooseError","httpStatus":null,"severity":"error","filePath":"lib/drivers/node-mongodb-native/connection.js","lineNumber":248,"sourceCode":" */\n\nNativeConnection.prototype.createClient = async function createClient(uri, options) {\n  if (typeof uri !== 'string') {\n    throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +\n      `string, got \"${typeof uri}\". Make sure the first parameter to ` +\n      '`mongoose.connect()` or `mongoose.createConnection()` is a string.');\n  }\n\n  if (this._destroyCalled) {\n    throw new MongooseError(\n      'Connection has been closed and destroyed, and cannot be used for re-opening the connection. ' +\n      'Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`.'\n    );\n  }\n\n  if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {\n    if (this._connectionString !== uri) {\n      throw new MongooseError('Can\\'t call `openUri()` on an active connection with ' +\n        'different connection strings. Make sure you aren\\'t calling `mongoose.connect()` ' +\n        'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections');\n    }\n  }\n\n  options = processConnectionOptions(uri, options);\n\n  if (options) {\n\n    const autoIndex = options.config?.autoIndex ?? options.autoIndex;\n    if (autoIndex != null) {\n      this.config.autoIndex = autoIndex !== false;\n      delete options.config;\n      delete options.autoIndex;\n    }\n\n    if ('autoCreate' in options) {\n      this.config.autoCreate = !!options.autoCreate;","sourceCodeStart":230,"sourceCodeEnd":266,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/drivers/node-mongodb-native/connection.js#L230-L266","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Disconnect first: await mongoose.disconnect(); await mongoose.connect(uriB);.","For concurrent databases, use separate connections: const connB = mongoose.createConnection(uriB) instead of switching the default.","Make bootstrap idempotent: connect once, cache the promise, never call connect() per request or per module reload."],"exampleFix":"// before\nawait mongoose.connect(process.env.MONGO_URI_A);\n// later, same process:\nawait mongoose.connect(process.env.MONGO_URI_B); // throws\n\n// after\nawait mongoose.disconnect();\nawait mongoose.connect(process.env.MONGO_URI_B);\n// or keep both alive:\nconst connB = await mongoose.createConnection(process.env.MONGO_URI_B).asPromise();","handlingStrategy":"fallback","validationCode":"let connectedUri = null;\nasync function connectOnce(uri) {\n  if (connectedUri === uri && mongoose.connection.readyState === 1) {\n    return mongoose.connection.asPromise();\n  }\n  if (mongoose.connection.readyState !== 0) {\n    await mongoose.disconnect();\n  }\n  const conn = await mongoose.connect(uri);\n  connectedUri = uri;\n  return conn;\n}","typeGuard":null,"tryCatchPattern":"try {\n  await mongoose.connect(uri);\n} catch (err) {\n  if (err instanceof mongoose.MongooseError && err.message.includes('different connection strings')) {\n    await mongoose.disconnect();\n    return mongoose.connect(uri); // retry once on a clean connection\n  }\n  throw err;\n}","preventionTips":["Call connect() exactly once per process and cache/share the promise.","Use createConnection() per database when multiple URIs must coexist.","In dev with HMR, guard bootstrap with a globalThis flag so re-execution is a no-op."],"tags":["mongoose","connect","multiple-connections","hmr","testing"],"backgroundTag":"connection-string-mismatch","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}