如何使用 mongodb 驱动程序来监视数据库中的更改,同时使用 mongoose 进行数据库连接。Mongoose 文档提供了很少的关于如何使用变更流的示例。在我的情况下,更改流仅在没有提供管道选项时才起作用。我认为这是管道对象的语法问题,但我仔细遵循了 mongodb 文档中的示例。问题要么在于管道对象,要么在于更改流是如何使用 mongoose 实现的。任何帮助表示赞赏。
这是我目前的方法(不起作用):
mongoose
.connect(db, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
// useCreateIndex: true
})
.then(() => {
console.log("Connected to MongoDB...");
})
.catch(err => {
console.log(err);
});
const pipeline = {
$match: {
$or: [{ operationType: 'insert' },{ operationType: 'update' }],
'fullDocument.institution': uniId
}
};
const options = { fullDocument: 'updateLookup' }
changeStream.on("change", next => {
switch(next.operationType) {
case 'insert':
console.log('an insert happened...', "uni_ID: ", next.fullDocument.institution);
let rooms = Object.keys(socket.rooms);
console.log("rooms: ", rooms);
nmsps.emit('insert', {
type: 'insert',
msg: 'New question available',
newPost: next.fullDocument
});
break;
case 'update':
console.log('an update happened...');
nmsps.emit('update', {
type: 'update',
postId: next.documentKey._id,
updateInfo: next.updateDescription.updatedFields,
msg: "Question has been updated."
});
break;
case 'delete':
console.log('a delete happened...');
nmsps.emit('delete', {
type: 'delete',
deletedId: next.documentKey._id,
msg: 'Question has been deleted.'
});
break;
default:
break;
}
})