如何在NodeJS中使用Mongoose从MongoDB变更流中获取fullDocumentBeforeChange?

vnjpjtjt  于 2022-12-22  发布在  Go
关注(0)|答案(1)|浏览(175)

我正在使用Mongoose、MongoDB和Nodejs,我想监听MongoDB集合的更改,并在更改前控制台记录文档和更新描述。
实际结果:我只能记录更新说明。

const didChangeStream = model.collection.watch({
  fullDocument: 'updateLookup',
  fullDocumentBeforeChange: 'whenAvailable'
});
didChangeStreamAlert.on('change', async (event) => {
  const {
    documentKey,
    fullDocument,
    fullDocumentBeforeChange,
    updateDescription
  } = event;
  console.log('fullDocumentBeforeChange', fullDocumentBeforeChange);
  console.log('updateDescription', updateDescription);
});
wydwbb8l

wydwbb8l1#

https://mongoosejs.com/docs/api.html#model_Model-watch 说选项是第二个参数,所以必须是

const didChangeStream = model.watch([], {
  fullDocument: 'updateLookup',
  fullDocumentBeforeChange: 'whenAvailable'
});

而且它应该在模型级别上工作。不需要直接触摸model.collection

相关问题