Node.js listen to MongoDB change

2020-06-21 05:26发布

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?

4条回答
叛逆
2楼-- · 2020-06-21 06:07

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);
});
查看更多
成全新的幸福
3楼-- · 2020-06-21 06:12

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);
});
查看更多
等我变得足够好
4楼-- · 2020-06-21 06:18

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.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-06-21 06:23

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.

查看更多
登录 后发表回答