Nest js mongoose日志连接事件

blmhpbnm  于 2023-08-06  发布在  Go
关注(0)|答案(3)|浏览(66)

我在express中做了类似的事情来记录mongodb连接事件。

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');
});

字符串
我想在Nest js中有这样的东西,但我不能这样做。下面是我连接到mongodb的nest js代码。

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 {}

vnjpjtjt

vnjpjtjt1#

您可以在app.module.ts文件中监视NestJS mongodb连接,同时通过url连接mongodb。

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

字符串
https://docs.nestjs.com/techniques/mongodb

bvhaajcl

bvhaajcl2#

我终于找到了答案。我应该使用InjectConnection

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

字符串

xxhby3vn

xxhby3vn3#

在调用connectionFactory之前,db连接已经完成,connection.on('connected',...)事件没有发生
您可以通过mongoose connection的readyStates https://mongoosejs.com/docs/api.html#connection_Connection-readyState检查它是否已连接

MongooseModule.forRoot(`${url}`, {
  connectionFactory: (connection: Connection) => {
    if (connection.readyState === 1) {
      Logger.log('DB connected');
    }

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

    return connection;
  },
}),

字符串
关于断线,回答上面的工作

相关问题