简体   繁体   English

MongoDb 节点 js 带有更改流的实时通知

[英]MongoDb Node js Real Time notifications with change streams

In my web application i have followers and notifications.在我的 web 应用程序中,我有关注者和通知。 The problem is how to get to the list of users and report changes of some document like changed price, or user created one more property etc.. So i can use change streams to watch for changes inside collection.问题是如何获取用户列表并报告某些文档的更改,例如更改的价格,或者用户创建了更多属性等。所以我可以使用更改流来观察集合内的更改。

Property.watch().
on('change', async data => {
  let prop = await Property.findById(data.documentKey._id);
  let user = await Follow.findOne({userId: prop.user._id});

  // After that find all followers then 
  user.followers.forEach(foll => {
    await Notification.create({
      ...
    })
  })
});

This code looks crazy to me, I mean even with some validations etc.. this is again overkill.这段代码对我来说看起来很疯狂,我的意思是即使有一些验证等。这又是矫枉过正。

Maybe better approach is some logic inside controller, but how i can first return response to user after he successfully created or updated document and then run some function where i can find all users on followers list and create notifications for them?也许更好的方法是 controller 内部的一些逻辑,但是我如何在他成功创建或更新文档后首先向用户返回响应,然后运行一些 function 我可以在其中找到关注者列表中的所有用户并为他们创建通知?

What you guys think?你们怎么看? There is not much examples and solutions for notification system, is there any resource that can be helpful通知系统的示例和解决方案不多,是否有任何资源可以提供帮助

Change streams support filtering and other functionality.变更流支持过滤和其他功能。

So basically i ended up with code like this.所以基本上我最终得到了这样的代码。 Inside update and create controller i'm creating user activity and then i'm watching that model.内部更新并创建 controller 我正在创建用户活动,然后我正在观看 model。

Activity.watch().on('change', async (data) => {
  const { fullDocument } = data;
  const followers = await Follow.findOne({ user: fullDocument.user});
  if(!followers) return;

  let doc = [];

  followers.followers.forEach(follower => {
    let obj = {};

    obj.senderId = fullDocument.user;
    obj.receiverId = follower;
    obj.message = fullDocument.activityMessage;

    doc.push(obj);
  })

  try {
    await Notification.insertMany(doc);
  } catch(err) {
    console.log(err);
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM