我正在尝试使用更改流来监听我的 mongodb 集群中的更改;但是在学习了几个教程之后,我使用猫鼬的最终实现不起作用。如何使用当前的猫鼬连接来监听数据库中的变化
猫鼬连接:
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 changeStream = Post.watch([pipeline], {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;
}
})