nestjs / mongoose

Mongoose module for Nest framework (node.js) 🍸
https://nestjs.com
MIT License
530 stars 118 forks source link

feat: added onconnectioncreate module option #2096

Closed prateekkathal closed 7 months ago

prateekkathal commented 8 months ago

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

// THIS DOES NOT WORK
MongooseModule.forRootAsync({
  imports: [MongoConfigModule],
  useFactory: async (mongoConfigService: MongoConfigService) => {
    return {
      ...mongoConfigService.mongoConfig,
      connectionFactory: (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],
}),

What is the new behavior?

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?

Other information

I can create the Main Docs PR if changes are approved.

kamilmysliwiec commented 7 months ago

lgtm