Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 MongoDB, and fire an event if a change happens?

like image 213
murvinlai Avatar asked Sep 28 '11 18:09

murvinlai


People also ask

How do I watch changes in MongoDB?

You can watch for changes in MongoDB using the watch() method on the following objects: Collection. Database. MongoClient.

How does MongoDB change stream work?

Change streams transform a MongoDB database into a real-time database by taking advantage of MongoDB's replication process. They monitor replication in MongoDB, providing an API for external applications that require real-time data without the risk involved in tailing the oplog or the overhead that comes with polling.

How does node js connect to MongoDB?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

Can we use MongoDB with node js?

MongoDB is a modern, general-purpose document-oriented data platform that has been widely paired with Node. js in popular tech stacks such as the MEAN stack (MongoDB, Express. js, AngularJS, and Node. js) and the MERN stack (MongoDB, Express.


2 Answers

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);
});
like image 143
Brandon Avatar answered Sep 19 '22 23:09

Brandon


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.

like image 36
maerics Avatar answered Sep 17 '22 23:09

maerics