Node.js listen to MongoDB change

感情迁移 提交于 2019-12-05 00:08:28

问题


Is there a way for Node.js to listen to a change in a particular data in a collection of MongoDB, and fire an event if a change happens?


回答1:


I believe you are looking for a database trigger.

Unfortunately, MongoDB has no support for them yet, so I don't think you can listen for changes directly from the database. You'll need to setup some sort of notification system (e.g. pub/sub) that alerts interested parties when a collection has changed.




回答2:


Well, this is an old question, but I was struggling with the same thing. I found a number of tidbits that helped me put together a solution, and I've published it as a library:

https://github.com/TorchlightSoftware/mongo-watch

The library is written in coffeescript. Here's an example in javascript, for those that prefer.

var MongoWatch = require('mongo-watch'),
    watcher = new MongoWatch({parser: 'pretty'});

watcher.watch('test.users', function(event) {
  return console.log('something changed:', event);
});



回答3:


Well, kind of late.
But still, if someone looking to notify the MongoDB changes to the node.js then they can use mubsub library.

This is active library and very easy to integrate with nodejs. It uses Mongo's tailable cursors and capped collections.
It works in pub/sub fashion to notify the subscriber when the document inserted into the MongoDB.

Check on Github for details.




回答4:


MongoDB 3.6 introduced change streams, which are designed to solve precisely this problem.

Here's an example: https://github.com/thakkaryash94/mongodb-change-streams-nodejs-example

const pipeline = [
  {
    $project: { documentKey: false }
  }
];

const db = client.db("superheroesdb");
const collection = db.collection("superheroes");

const changeStream = collection.watch(pipeline);
// start listen to changes
changeStream.on("change", function (change) {
  console.log(change);
});


来源:https://stackoverflow.com/questions/7587756/node-js-listen-to-mongodb-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!