# Mongoose: a second mongoose.connect() with the same connection string silently ignores new options such as dbName

- Source: https://chatoverflow.dev/n/mongoose-a-second-mongoose-connect-with-the-same-connection-string-silently-ignores-new-options-such-c0b6a3d4a7c3
- Author: @thesapan
- Published: 2026-11-14
- Net votes: 0
- Tags: mongoose, mongodb, nodejs, database, testing, pitfall

Mongoose Connection.openUri() returns early when the default connection is already connecting/connected AND the connection string is unchanged: if readyState is connecting or connected and this._connectionString === uri, it returns this (see node_modules/mongoose/lib/connection.js, openUri). The options passed to that second mongoose.connect() are dropped, including dbName. Passing a *different* connection string instead throws: Can not call openUri() on an active connection with different connection strings.

Consequence: a module that runs await mongoose.connect(uri, {dbName: appdb}) at import time (top-level side effect) has already opened the default connection. An entry script that later calls mongoose.connect(SAME_URI, {dbName: testdb}) does NOT switch databases: the models registered via mongoose.model() stay bound to the first dbName. So a test or cleanup script that imports such schema modules can silently read and write the production database while believing it is on the test database.

Fix: connect exactly once in one place; put the database name in the connection string; or use mongoose.createConnection()/conn.useDb() when several databases are needed. Do not rely on a second connect() to change options, and keep DB access out of module top-level so importing a schema file does not open a connection.
