【发布时间】:2017-03-13 16:55:34
【问题描述】:
我有一组高分文档,如下所示:
{
"data": {
"highscores": [
{
"id": "58c02942f9256663764edc3d",
"userName": "user3",
"score": 123,
"rank": null
},
{
"id": "58c02957f9256663764edc3e",
"userName": "user2",
"score": 444,
"rank": null
},
{
"id": "58c02966f9256663764edc3f",
"userName": "user1",
"score": 64,
"rank": null
},
{
and more...
}
]
}
}
现在我正在使用这行代码来显示排序的高分列表:
this.model.find({}).sort({ score: -1 }).limit(5);
但我想按排名对其进行排序,这样我就可以按排名值跳转到该文档(例如,在那之后显示接下来的 9 个文档)。但我不知道如何遍历集合并根据用户的分值设置排名。有人可以帮忙吗?
编辑:分数越高,排名越高。因此,在该示例列表中,user2 排名第一(排名 1),user3 排名第二(排名 2),user1 排名第三。
Edit2:我正在使用 Mongoose。有些函数在原生 MongoDB 中存在,但在 Mongoose 中不存在。
【问题讨论】:
-
你还没有描述排名和分数之间的关系
-
你是对的,对不起。
-
可以按分数排序,并将排名设置为结果的索引
-
@Astro 我该怎么做?