@@ -10,7 +10,7 @@ mongoose.set('strictQuery', false);
1010const log = logger . extend ( 'mongoose' ) ;
1111
1212// Cache for connections
13- const mongooseConnections = { } ;
13+ const mongooseConnectionPromises = { } ;
1414
1515/**
1616 * Returns a Mongoose connection for a given server and db name.
@@ -20,38 +20,29 @@ const getMongoose = async ({ server = mongoConfig.host, db } = {}) => {
2020 if ( ! db ) throw new Error ( 'Missing db name' ) ;
2121
2222 // Return existing connection if present
23- if ( mongooseConnections [ server ] ?. [ db ] ) {
23+ if ( mongooseConnectionPromises [ server ] ?. [ db ] ) {
2424 log ( `Using cached connection: ${ server } ${ db } ` ) ;
25- return mongooseConnections [ server ] [ db ] ;
25+ return await mongooseConnectionPromises [ server ] [ db ] ;
2626 }
2727
2828 log ( `Creating new connection: ${ server } ${ db } ` ) ;
2929 const uri = `${ server } ${ db } ` ;
30- const connection = mongoose . createConnection ( uri , {
31- // Removed deprecated options
32- // useNewUrlParser and useUnifiedTopology are defaults in Mongoose 8+
33-
34- autoIndex : mongoConfig . createIndex ?? false , // Create indexes if needed
35- autoCreate : true , // Ensure collections are auto-created
36- bufferCommands : false , // ❗ Important for strict connection behavior in Mongoose 8+
37- } ) ;
38-
39- // Cache the connection
40- mongooseConnections [ server ] = mongooseConnections [ server ] || { } ;
41- mongooseConnections [ server ] [ db ] = connection ;
42-
43- // Return promise that resolves once connected
44- return new Promise ( ( resolve , reject ) => {
45- connection . once ( 'open' , ( ) => {
46- log ( `Connected to ${ server } ${ db } ` ) ;
47- resolve ( connection ) ;
48- } ) ;
49-
50- connection . on ( 'error' , ( err ) => {
51- log ( `Connection error on ${ server } ${ db } :` , err ) ;
52- reject ( err ) ;
53- } ) ;
54- } ) ;
30+ const connectionPromise = mongoose
31+ . createConnection ( uri , {
32+ // Removed deprecated options
33+ // useNewUrlParser and useUnifiedTopology are defaults in Mongoose 8+
34+
35+ autoIndex : mongoConfig . createIndex ?? false , // Create indexes if needed
36+ autoCreate : true , // Ensure collections are auto-created
37+ bufferCommands : false , // ❗ Important for strict connection behavior in Mongoose 8+
38+ } )
39+ . asPromise ( ) ;
40+
41+ // Cache the connection promise
42+ mongooseConnectionPromises [ server ] = mongooseConnectionPromises [ server ] || { } ;
43+ mongooseConnectionPromises [ server ] [ db ] = connectionPromise ;
44+
45+ return await connectionPromise ;
5546} ;
5647
5748export { getMongoose } ;
0 commit comments