Skip to content

Instantly share code, notes, and snippets.

@jpaljasma
Last active December 5, 2019 23:07
Show Gist options
  • Save jpaljasma/3260eaa6f7a40315863d to your computer and use it in GitHub Desktop.
Save jpaljasma/3260eaa6f7a40315863d to your computer and use it in GitHub Desktop.
How to subscribe for new MongoDB documents in Node.js using tailable cursor
/**
* How to subscribe for new MongoDB documents in Node.js using tailable cursor
*/
// subscriber function
var subscribe = function(){
var args = [].slice.call(arguments);
var next = args.pop();
var filter = args.shift() || {};
if('function' !== typeof next) throw('Callback function not defined');
// connect to MongoDB
require('mongodb').MongoClient.connect('mongodb://localhost/test', function(err, db){
// make sure you have created capped collection "messages" on db "test"
db.collection('messages', function(err, coll) {
// seek to latest object
var seekCursor = coll.find(filter).sort({$natural: -1}).limit(1);
seekCursor.nextObject(function(err, latest) {
if (latest) {
filter._id = { $gt: latest._id }
}
// set MongoDB cursor options
var cursorOptions = {
tailable: true,
awaitdata: true,
numberOfRetries: -1
};
// create stream and listen
var stream = coll.find(filter, cursorOptions).sort({$natural: -1}).stream();
// call the callback
stream.on('data', next);
});
});
});
};
// new documents will appear in the console
subscribe( function(document) {
console.log(document);
});
@ajaytlabs
Copy link

its working only remove /* sort({$natural: -1}) */ from this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment