In trying to limit the number of connections in my web application I switched from using mongoose.createConnection() to mongoose.connect()
Which works perfectly if your only ever using one database. Unfortnately for me Im using a couple and wanted to switch between them easily and effortlessly without creating new connections or leaving room for edge cases.
I found that you can use mongoose.connection.useDB() to change the the db without creating a new connection pool. This function then returns a new connection object that can be used. But for some reason mongoose.connection.db.databaseName which should return the default connection database name does not show the change.
here is the code
export async function dbConnect(dbName){
const options = {
dbName: dbName,
socketTimeoutMS: 20000
}
try{
if(mongoose.connection.db){
console.log("already a connection: checking name")
if(mongoose.connection.db.databaseName === dbName){
console.log("name is the same")
return
}else{
console.log("changing db")
const newconnection = mongoose.connection.useDb(dbName, { useCache: true })
console.log(await newconnection.db.databaseName)
}
}
else {await mongoose.connect(process.env.MONGODB_URI, options)}
}catch(error){
console.log(error)
}
}
Note that the console.log(await newconnection.db.databaseName) does log the new database name but mongoose.connection.db.databaseName does not.
Obviously, this is much less a problem and more of question of how the mongoose connection system works. I’m wondering if mongoose.connection.db is set to the first database that is connected to and permantely fallsback to that if .useDb() is not explicitly used. Meaning it cannot be changed and .useDb() only allows you to breifly access a different db through the returned new connection object?
I just started working with mongoose so please excuse any errors and if such answers are directly stated in the their documents.