如果您将 mongodb 与 WiredTiger storageEngine 一起使用,您可以使用 collection.watch() 函数并在您的羽毛应用程序中添加一个类似这样的监视器
//src/services/monitor.js
module.exports = function(app){
//get mongo client
const mongoClient = app.get('mongoClient');
//connect db
mongoClient.then(db => {
//collection to watch
const collection = db.collection('your_collection_name')
//watch collection
const changeStream = collection.watch({ fullDocument: 'updateLookup' });
//on some data changed
changeStream.on('change', data => {
console.log ( 'something is changed in your collection' , data )
//your service.emit
});
})
}
然后我在/src/services/index.js 中添加了这个简单的监视器(可能不是正确的方法,但它有效)
//src/services/index.js
...
const monitor = require('./monitor.js');
module.exports = function (app) {
...
app.configure(monitor);
...
};
集合每次更改时返回的数据
{ _id:
{ _data:
'825C7F03230000001C29295A100490DEF2C65812410FABF0DE46F9C89D7246645F696400645C1AC097B189CBD5D4A24D330004' },
operationType: 'replace',
clusterTime:
Timestamp { _bsontype: 'Timestamp', low_: 28, high_: 1551827747 },
fullDocument:
{ _id: 5c1ac097b189cbd5d4a24d33,
id: '12',
language: 'it-IT',
category: 'some data',
slug: '',
description: 'some data',
src:'',
color: 'card',
status: true,
home: true,
order_int: '3',
visual: 'card' },
ns: { db: 'mydb', coll: 'mycollection' },
documentKey: { _id: 5c1ac097b189cbd5d4a24d33 } }
更多信息在这里https://docs.mongodb.com/manual/reference/method/db.collection.watch/