@@ -8,29 +8,40 @@ const logger = getLogger('mongoose');
88
99const mongooseConnections = { } ;
1010
11+ /**
12+ * Connects to a MongoDB instance and returns a Mongoose connection.
13+ *
14+ * Mongoose v8 Notes:
15+ * - `bufferCommands: false` disables legacy buffering behavior.
16+ * - `createConnection()` is preferred over `connect()` for scoped, multi-db setups.
17+ * - This loader reuses existing connections per `server + db` pair.
18+ */
1119const _getMongoose = async ( { server = mongoConfig . host , db } = { } ) => {
1220 try {
13- if ( db === undefined ) {
14- throw Error ( 'missing db name' ) ;
15- }
16- if ( mongooseConnections [ server ] && mongooseConnections [ server ] [ db ] ) {
21+ if ( ! db ) throw new Error ( 'missing db name' ) ;
22+
23+ if ( mongooseConnections [ server ] ?. [ db ] ) {
1724 logger . debug ( `reusing connection ${ server } ${ db } ` ) ;
18- return await mongooseConnections [ server ] [ db ] ;
25+ return mongooseConnections [ server ] [ db ] ;
1926 }
27+
2028 logger . log ( `creating connection ${ server } ${ db } ` ) ;
2129 mongooseConnections [ server ] = mongooseConnections [ server ] || { } ;
22- mongooseConnections [ server ] [ db ] = mongoose
23- . createConnection ( `${ server } ${ db } ` , {
24- useNewUrlParser : true ,
25- useUnifiedTopology : true ,
26- autoIndex : mongoConfig . createIndex || false ,
27- } )
28- . asPromise ( ) ;
29- const connection = await mongooseConnections [ server ] [ db ] ;
30+
31+ 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+ } ) ;
36+
37+ mongooseConnections [ server ] [ db ] = connection ;
38+
39+ await connection . asPromise ( ) ;
3040 logger . log ( `opened connection ${ server } ${ db } ` ) ;
41+
3142 return connection ;
3243 } catch ( error ) {
33- logger . warn ( 'getMongoose' , error ) ;
44+ logger . warn ( 'getMongoose() failed ' , error ) ;
3445 throw error ;
3546 }
3647} ;
0 commit comments