diff --git a/lib/interfaces/mongoose-options.interface.ts b/lib/interfaces/mongoose-options.interface.ts index 4ce30808..7e6176d9 100644 --- a/lib/interfaces/mongoose-options.interface.ts +++ b/lib/interfaces/mongoose-options.interface.ts @@ -1,5 +1,5 @@ import { ModuleMetadata, Type } from '@nestjs/common'; -import { ConnectOptions, MongooseError } from 'mongoose'; +import { ConnectOptions, MongooseError, Connection } from 'mongoose'; export interface MongooseModuleOptions extends ConnectOptions { uri?: string; @@ -9,6 +9,7 @@ export interface MongooseModuleOptions extends ConnectOptions { connectionFactory?: (connection: any, name: string) => any; connectionErrorFactory?: (error: MongooseError) => MongooseError; lazyConnection?: boolean; + onConnectionCreate?: (connection: Connection) => void; } export interface MongooseOptionsFactory { diff --git a/lib/mongoose-core.module.ts b/lib/mongoose-core.module.ts index f416e3e0..528083f2 100644 --- a/lib/mongoose-core.module.ts +++ b/lib/mongoose-core.module.ts @@ -43,6 +43,7 @@ export class MongooseCoreModule implements OnApplicationShutdown { connectionFactory, connectionErrorFactory, lazyConnection, + onConnectionCreate, ...mongooseOptions } = options; @@ -69,6 +70,7 @@ export class MongooseCoreModule implements OnApplicationShutdown { uri, mongooseOptions, lazyConnection, + onConnectionCreate, ), mongooseConnectionName, ), @@ -107,6 +109,7 @@ export class MongooseCoreModule implements OnApplicationShutdown { connectionFactory, connectionErrorFactory, lazyConnection, + onConnectionCreate, ...mongooseOptions } = mongooseModuleOptions; @@ -123,6 +126,7 @@ export class MongooseCoreModule implements OnApplicationShutdown { uri as string, mongooseOptions, lazyConnection, + onConnectionCreate, ), mongooseConnectionName, ), @@ -191,6 +195,7 @@ export class MongooseCoreModule implements OnApplicationShutdown { uri: string, mongooseOptions: ConnectOptions, lazyConnection?: boolean, + onConnectionCreate?: MongooseModuleOptions['onConnectionCreate'], ): Promise { const connection = mongoose.createConnection(uri, mongooseOptions); @@ -198,6 +203,11 @@ export class MongooseCoreModule implements OnApplicationShutdown { return connection; } + const mongooseOnConnectionCreate = onConnectionCreate || (() => {}); + if (mongooseOnConnectionCreate) { + mongooseOnConnectionCreate(connection); + } + return connection.asPromise(); }