首页 > 解决方案 > 如何通过changestream监听mongodb数据库中的特定字段?

问题描述

我的 mongodb 数据库名称users上有一个集合,每个用户都包含一个字段名称posts。当用户添加新帖子或更新现有帖子并从套接字服务器获取更新值并将其发送回前端时,我想获取该帖子字段的实时更改数据。

单个用户文档看起来像这样

 [  
    {
        "_id" : "613fb31a52ef63541d036fcd",
        "posts"["613fb31a52ef63541d036fdf", "613fb31a52ef63541d036ff1"],
        "mobiles" : [ "01751150412"],
        "languages" : [ "English", "Bangla"],
     }
]

起初,我尝试过 const userChangeStream = connection.collection("users").watch()

这给了我用户集合的所有字段,甚至没有改变。

然后我按照这个stackoverflow问题更新了我的代码

 const filter = 
 [
   {
      $match: 
      {
        $and: 
        [
          { "updateDescription.updatedFields.posts": { $exists: true } },
          { operationType: "update" }
        ]
      }
   }
]

const options = { fullDocument: 'updateLookup' };

const postsChangeStream =    connection.collection("users").watch(filter,options);

postsChangeStream.on("change", (change) => {
  console.log('change on', change);
});

现在,在添加该帖子字段时我没有得到任何响应。

标签: javascriptmongodbsocketsreal-timechangestream

解决方案


推荐阅读