Hi everyone,
I am new in MongoDb and Nodejs.
I am having this error: (thanks for tour help!!)
matias@dell ~/nodejs $ node nuevo.js
/home/matias/nodejs/node_modules/mongodb/lib/utils.js:97
process.nextTick(function() { throw err; });
^
MongoError: Tailable cursor doesn't support sorting
at Cursor.sort (/home/matias/nodejs/node_modules/mongodb/lib/cursor.js:358:37)
at /home/matias/nodejs/nuevo.js:35:55
at handleCallback (/home/matias/nodejs/node_modules/mongodb/lib/utils.js:95:12)
at /home/matias/nodejs/node_modules/mongodb/lib/cursor.js:513:5
at handleCallback (/home/matias/nodejs/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:248:5)
at nextFunction (/home/matias/nodejs/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:638:5)
at /home/matias/nodejs/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:563:7
at queryCallback (/home/matias/nodejs/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:224:5)
at Callbacks.emit (/home/matias/nodejs/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:95:3)
at null.messageHandler (/home/matias/nodejs/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:246:23)
matias@dell ~/nodejs $
I am runing mongoDB 3.0.4 and nodejs 0.12.6 and here is my code (i have already created a chat db and a collection called "messages":
/**
* 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/chat', 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);
});