Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest js mongoose log connection event

I do something like this in express to log mongodb connection events.

mongoose
  .connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useFindAndModify: false
  })
  .then(() => console.log('connect to DB successfully :)'));

mongoose.connection.on('error', err => {
  console.log('DB connection failed');
});

mongoose.connection.on('disconnected', () => {
  console.log('DB disconnected');
});

mongoose.connection.on('reconnected', () => {
  console.log('DB reconnected');
});

I want something like that in Nest js but I can't do that. here is my nest js code to connect to mongodb.

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  controllers: [AppController],
  providers: [AppService],
  imports: [
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.get<string>('dbConnectionString'),
        user: configService.get<string>('DB_USER'),
        pass: configService.get<string>('DB_PASS')
      }),
      inject: [ConfigService]
    })
  ]
})
export class AppModule {}
like image 746
علی سالمی Avatar asked Dec 05 '25 04:12

علی سالمی


2 Answers

You can monitor NestJS mongodb connection inside of your app.module.ts file while connecting mongodb by url.

    MongooseModule.forRoot(dbURL, {
      connectionFactory: (connection) => {
        connection.on('connected', () => {
           console.log('is connected');
        });
        connection._events.connected();
        return connection;
        },
      },
    ),

https://docs.nestjs.com/techniques/mongodb

like image 84
kumol Avatar answered Dec 08 '25 17:12

kumol


Finally I found an answer. I should use InjectConnection.

@Injectable()
export class AppService {
  constructor(@InjectConnection() private connection: Connection) {
    this.connection.on('disconnected', () => {
      console.log('DB disconnected');
    });
  }
}

like image 40
علی سالمی Avatar answered Dec 08 '25 18:12

علی سالمی



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!