【发布时间】:2016-01-06 21:38:16
【问题描述】:
我有一个名为 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
}
【问题讨论】:
标签: javascript mongodb mongoose mongodb-query aggregation-framework