Reversing the .each() order (mongodb)
-
27-10-2019 - |
Question
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));
}
});
Solution
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
OTHER TIPS
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});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow