我正在监听我的 mongoDB replicaSet 中的变化,并使用 { fullDocument: 'updateLookup' }
获取 fullDocument 以及 operationType
的更改字段 更新
如果 operationType
是 update
,我想从 fullDocument 中删除某些字段
这是我做的,
const filter = [{"$match":{"operationType":"update"}}, {"$project":{ "fullDocument._id": 0, "fullDocument.channel": 0, "fullDocument.user_id": 0, "fullDocument.first_name": 0, "fullDocument.last_name": 0, "fullDocument.profile_pic": 0, "fullDocument.email": 0, "fullDocument.number": 0, "fullDocument.updatedAt": 0, "fullDocument.createdAt": 0, "fullDocument.__v": 0}}];
const userDBChange = userChatModel.watch(filter, { fullDocument: 'updateLookup' });
这里的问题是,我没有收到任何其他更改,例如 - 插入。
我发现问题出在使用 "$match":{"operationType":"update"}
如果我删除它,我会收到插入更改更新,但 $project
应用于它。
有没有办法只在 operationType:'update'
上应用 $project
,同时仍然让其他更改保持不变(不对其应用过滤器)?
最佳答案
经过几天的学习和尝试新事物,我终于解决了这个问题。
我做了以下事情:
const filter =
[{ "$match":
{ "operationType": {"$in" :["update", "insert"]} } },
{ "$project": {
"fullDocument": {
"$cond":{
"if":{
"$eq":["$operationType", "update"]
},
"then":"$fullDocument.client",
"else":"$fullDocument"
}
}
}
}];
const userDBChange = userChatModel.watch(filter, { fullDocument: 'updateLookup' });
编码愉快,谢谢!
关于node.js - 仅当 mongodb 中的 operationType 为 'update' 时才过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618233/