我在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 {}
型
3条答案
按热度按时间vnjpjtjt1#
您可以在
app.module.ts
文件中监视NestJS mongodb连接,同时通过url连接mongodb。字符串
https://docs.nestjs.com/techniques/mongodb
bvhaajcl2#
我终于找到了答案。我应该使用
InjectConnection
。字符串
xxhby3vn3#
在调用connectionFactory之前,db连接已经完成,
connection.on('connected',...)
事件没有发生您可以通过mongoose connection的readyStates https://mongoosejs.com/docs/api.html#connection_Connection-readyState检查它是否已连接
字符串
关于断线,回答上面的工作