我四处寻找如何在 NestJs 中实现 mongoDb 更改流,但到目前为止,我找不到任何解决方案或文档。
使用 Hooks 中间件也有类似的方法,但是如果我们从外部应用程序更改数据,则无法触发此方法。
@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: Cat.name,
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
const schema = CatsSchema;
schema.post('save', function() {
console.log(
`${configService.get('APP_NAME')}: Hello from post save`,
),
});
return schema;
},
inject: [ConfigService],
},
]),
],
})
export class AppModule {}
我找到了这个文档https://www.mongodb.com/docs/manual/changeStreams/但我们如何在 NestJs 中实现这一点呢?
最佳答案
像这样的东西应该可以工作。我无法对此进行测试,因为我没有设置副本集。
@Injectable()
export class ChangeStreamService implements OnModuleInit {
constructor(@InjectModel(Schema.name) private schemaModel: Model<SchemaDocument>) {}
onModuleInit() {
this.schemaModel.collection.watch<SchemaDocument>().on('change', (e) => {
console.log(e)
})
}
}
关于MongoDb 在 NestJs 中的变更流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73413782/