@@ -6,7 +6,8 @@ import { traceAll } from '../utils/trace.js';
66const mongoConfig = config . mongo ;
77const logger = getLogger ( 'mongoose' ) ;
88
9- const mongooseConnections = { } ;
9+ // cache for connections
10+ const mongooseConnectionPromises = { } ;
1011
1112/**
1213 * Connects to a MongoDB instance and returns a Mongoose connection.
@@ -20,23 +21,26 @@ const _getMongoose = async ({ server = mongoConfig.host, db } = {}) => {
2021 try {
2122 if ( ! db ) throw new Error ( 'missing db name' ) ;
2223
23- if ( mongooseConnections [ server ] ?. [ db ] ) {
24+ if ( mongooseConnectionPromises [ server ] ?. [ db ] ) {
2425 logger . debug ( `reusing connection ${ server } ${ db } ` ) ;
25- return mongooseConnections [ server ] [ db ] ;
26+ return await mongooseConnectionPromises [ server ] [ db ] ;
2627 }
2728
2829 logger . log ( `creating connection ${ server } ${ db } ` ) ;
29- mongooseConnections [ server ] = mongooseConnections [ server ] || { } ;
30+ mongooseConnectionPromises [ server ] =
31+ mongooseConnectionPromises [ server ] || { } ;
3032
3133 const uri = `${ server } ${ db } ` ;
32- const connection = mongoose . createConnection ( uri , {
33- autoIndex : mongoConfig . createIndex || false ,
34- bufferCommands : false , // ⛔ Disable buffering (required in Mongoose 8+)
35- } ) ;
34+ const connectionPromise = mongoose
35+ . createConnection ( uri , {
36+ autoIndex : mongoConfig . createIndex || false ,
37+ bufferCommands : false , // ⛔ Disable buffering (required in Mongoose 8+)
38+ } )
39+ . asPromise ( ) ;
3640
37- mongooseConnections [ server ] [ db ] = connection ;
41+ mongooseConnectionPromises [ server ] [ db ] = connectionPromise ;
3842
39- await connection . asPromise ( ) ;
43+ const connection = await connectionPromise ;
4044 logger . log ( `opened connection ${ server } ${ db } ` ) ;
4145
4246 return connection ;
0 commit comments