Get last messages and change sort order


#1

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});

#3

{sort: { created_at: 1}


#4

@nxcong Then I get the first 20 records of all time - but I want the latest 20 and then sort this 20 ones from oldest to newest.


#5

Have you tried publishing (with limit: 20) in descending then doing the client-side query in ascending sort order?


#6

Something like this :

Items
//result : 
[
{v : 1},
{v : 2},
{v : 3},
...
{v : 100}
]
Meteor.publish('getLatestItems', function(){
    return Items.find({},{sort : {v : -1},limit : 20}); //return v : 100 -> 80
});
//Client
Meteor.subscribe('getLatestItems');
Items.find() // return v : 80 -> 100

#7

@nxcong @hellstad Argh…how could I forgot it :smiley: - yeah, that solution works.