0

using mongodb with mongoose:

My current code returns the correct docs but sends them to the client in the wrong order. I tried adding another sort command after the .limit() to reverse this but it hasn't been working well. Any ideas to make this happen within the db call instead of extra code to reverse the order?

Item.find().sort('_id','descending').limit(40).each(function(err, doc) {
    if(doc != null){
        client.send(JSON.stringify(doc));       
    }
});
Community
  • 1
  • 1
fancy
  • 48,619
  • 62
  • 153
  • 231
  • How is it not working well? Is there an easy `reverse()` method you can use rather than trying to sort them again? – sarnold Apr 29 '11 at 07:36
  • @sarnold `Item.find().sort('_id','descending').limit(40).reverse().each(function(err, doc) {` returns an error TypeError: Object # has no method 'reverse' – fancy Apr 29 '11 at 07:44

2 Answers2

1

Depending on the actual context of your mongodb query try this (meteor client.js):

Item.find({}, { sort: { _id: -1 } })

or in db shell that code:

Item.find({}).sort({'_id': -1});
Hartmut
  • 11
  • 2
0

how about this?

var orderedList = new Array();
Item.find().sort('_id','descending').limit(40).each(function(err, doc) {
    orderedList.push(doc);
});

for (var i=orderedList.length; i>=0; i--){
   orderedList[i].doYourThang..
}

Try: JQuery .each() backwards for reverse() plugin

Community
  • 1
  • 1
Atticus
  • 6,585
  • 10
  • 35
  • 57
  • Hey thanks for the idea, if i was doing that I would need to do: `var orderedList = new Array(); Item.find().sort('_id','descending').limit(40).each( function(err, doc) { orderedList.push(doc); if (orderedList.length == 40) { for (var i=orderedList.length; i>=0; i--){ client.send(JSON.stringify(orderedList[i])); } } } );` – fancy Apr 29 '11 at 08:38
  • Oh right -- the doc is your response, duh :P Make sure you don't include the loop within the each function, you'll be iterating it over every each-iteration **** EDIT: just realized you had your if = 40 clause to handle that. – Atticus Apr 29 '11 at 08:41
  • But yeah -- there's no native reverse each function that I'm aware of. However, this may be of some use to you: http://stackoverflow.com/questions/1394020/jquery-each-backwards – Atticus Apr 29 '11 at 08:45