开发者

Node.js listen to MongoDB change

Is there a way for Node.js to listen to a change in a particular data in a collection of Mongo开发者_开发技巧DB, and fire an event if a change happens?


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);
});


MongoDB apparently now supports triggers and watch, this answer is outdated.

[Original] 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.


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);
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜