According to Mongoose Documentation, the event listeners should be added immediately after createConnection. By adding this onConnectionCreate function as a module option, we can bypass the limits of the connectionFactory function.
MongooseModule.forRootAsync({
imports: [MongoConfigModule],
useFactory: async (mongoConfigService: MongoConfigService) => {
return {
...mongoConfigService.mongoConfig,
// Once connection is established
connectionFactory: (connection: Connection) => {
connection.plugin(require('mongoose-autopopulate'));
return connection;
},
// Before connection is established and returned as Promise.
onConnectionCreate: (connection: Connection) => {
connection.on('connected', () => console.log('connected'));
connection.on('open', () => console.log('open'));
connection.on('disconnected', () => console.log('disconnected'));
connection.on('reconnected', () => console.log('reconnected'));
connection.on('disconnecting', () => console.log('disconnecting'));
return connection;
},
};
},
inject: [MongoConfigService],
}),
The same will work for forRootAsync().
Does this PR introduce a breaking change?
[ ] Yes
[x] No
Other information
I can create the Main Docs PR if changes are approved.
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Issue Number: #1290
What is the new behavior?
According to Mongoose Documentation, the event listeners should be added immediately after
createConnection
. By adding thisonConnectionCreate
function as a module option, we can bypass the limits of theconnectionFactory
function.The same will work for
forRootAsync()
.Does this PR introduce a breaking change?
Other information
I can create the Main Docs PR if changes are approved.