Following situation:
I get the latest messages of a chat with this helper:
'messages': function () {
return Messages.find({chat_id: this._id},{sort: { created_at: -1 }, limit: 20});
}
I’ll get this result:
{
_id: abc1
created_at: 1234
},
{
_id: abc2
created_at: 1233
},
{
_id: abc3
created_at: 1232
}
My problem: I need to change the results order to ASC, because I want the latest message at the bottom. In this case, the latest message is on the top and my chat view has the wrong message order.
Is there any direct MongoDB solution for that problem (because I also want to implement pagination later)? At this moment, my only idea is to change the order with underscore, but a direct Mongo solution would be the better way.
// Edit: My current solution is this, but I’m still looking for a clean MongoDB way:
var messages = Messages.find({chat_id: this._id},{sort: { created_at: -1}, limit:20}).fetch();
return _.sortBy(messages, function(message){ return message.created_at});