MongoDb 在 NestJs 中的变更流

标签 mongodb stream nestjs

我四处寻找如何在 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/

相关文章:

MongoDB $lookup 返回空数组

php - 如何将 stdin 的内容(直到 EOF)读入 PHP 中的字符串?

c# - 为什么 MemoryStream 不提供采用 "long"容量的构造函数?

cors - 在 NestJs 中启用 Cors

node.js - 嵌套计划 npm 不工作

arrays - 如何删除与 MongoDB $pull 条件不匹配的元素?

c++ - Mongo C++ 驱动程序 - 如何更改超时配置

mongodb - 在 MongoDB 中,您能从 shell 中看到命令行参数吗?

Java进程处理: keep correct order with output+error stream?

node.js - NestJS 加密 : What is the purpose of the promisify(scrypt)?