Reversing the .each() order (mongodb)
-
27-10-2019 - |
题
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));
}
});
解决方案
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
其他提示
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});
不隶属于 StackOverflow