We had this following query in our Node.JS
mongo.connect('mongodb://XXX:XXX@ds054XXX.mlab.com:54289/XXXdb', function (err, db) {
var collection = db.collection('chatmessages')
var stream = collection.find().sort({ _id: -1 }).limit(20).stream();
stream.on('data', function (chat) {
socket.emit('user message', chat.content, chat.dateCreated);
});
});
As you can see, the query is a collection of last 20 records entered. But then from this result we would like to do resort again to 1 in _id so in the list we will have ID 55 - 75 for instance (the order). So the last one always at the bottom.
How do we achieve this again?
You need to use the Aggregation Framework.
mongo.connect('mongodb://XXX:XXX@ds054XXX.mlab.com:54289/XXXdb', function (err, db) {
var collection = db.collection('chatmessages')
var stream = collection.aggregate([
{ "$sort": { "_id": -1}},
{ "$limit": 20 },
{ "$sort": { "_id": 1 }}
]);
stream.on('data', function (chat) {
socket.emit('user message', chat.content, chat.dateCreated);
});
});
The simplest thing to do will be to reverse the order of records returned by the query. So, instead of getting a stream, convert the response to array and use reverse() function, to reverse the order of records in it, before sending it through the socket!
mongo.connect('mongodb://XXX:XXX@ds054XXX.mlab.com:54289/XXXdb', function (err, db) {
var collection = db.collection('chatmessages')
collection.find().sort({ _id: _1 }).limit(20).toArray(function(err, docs) {
if (err) {
// handle error
}
docs.reverse(); // <-- This will reverse the order of records returned!
// Send the the array of records through socket.
socket.emit('user message', docs)
})
});