我有一个名为 article 的集合,需要按其包含的数组大小对返回的对象进行排序。最佳方法是什么? 我想到的一种方法是在 JS 中检索整个对象列表并手动排序。 但是我每次返回10篇文章,所以每次调用此API时都必须做不必要的数组排序工作。
Article.find({})
.limit(10)
.skip(req.params.page*10)
//Something like using $project to make a new variable called votecount that counts objects in a given array.
.sort({votecount:-1})
.exec(function(err,arts){
articleObj.articles = arts;
if (arts.length<10){
articleObj.reachedEnd = true;
}
res.json(articleObj);
});
我需要计算投票数。这是一个样本对象:
{
"_id" : ObjectId("55f50cfddcf1ad6931fb8dd4"),
"timestamp" : "2015-09-13T00:58:57-5:00",
"url" : "http://www.nytimes.com/2015/09/13/sports/floyd-mayweather-finishes-bout-and-maybe-his-career-with-lopsided-win-over-andre-berto.html",
"abstract" : "Mayweather’s victory by unanimous decision gave him a record of 49-0, the same as the legendary heavyweight Rocky Marciano.",
"title" : "Mayweather Wins Easily in What He Calls Last Bout",
"section" : "Sports",
"comments" : [ ],
"votes" : {
"up" : [
ObjectId("55e5e16934d355d61c471e48")
],
"down" : [ ]
},
"image" : {
"caption" : "Floyd Mayweather Jr. after learning he defeated Andre Berto in a unanimous decision.",
"url" : "http://static01.nyt.com/images/2015/09/14/sports/13fight/13fight-mediumThreeByTwo210.jpg"
},
"__v" : 0
}