node.js - 仅当 mongodb 中的 operationType 为 'update' 时才过滤

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我正在监听我的 mongoDB replicaSet 中的变化,并使用 { fullDocument: 'updateLookup' } 获取 fullDocument 以及 operationType 的更改字段 更新

如果 operationTypeupdate,我想从 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/

相关文章:

javascript - MongoDB-如果不存在则插入,否则跳过

javascript - 使用 POST 的 NodeJS 快速身份验证返回错误 发送后无法设置 header

node.js - Mongoose Model.find().select() 如果Select是空字符串返回什么?

ruby-on-rails - rails 3 : Call back for when a certain object is pulled from the database (Mongo Mapper)

javascript - 变量没有状态键,但 var.status 给出字符串

node.js - sequelize.sync 中没有方法成功

node.js - 使用 Angular 时有没有办法从服务器端加载部分 View ?

javascript - 在NodeJS中获取Mongo数据库中插入文档的_id

javascript - Mongoose:类型错误: 'mongooseSchemahere' 不是函数

javascript - Mongoose 查找/更新子文档