我有一组看起来像这样的高分文档:
{
"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...
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
现在我使用这行代码来显示一个排序的高分列表:
this.model.find({}).sort({ score: -1 }).limit(5);
Run Code Online (Sandbox Code Playgroud)
但我想按等级排序,这样我就可以按等级值跳转到该文档(例如显示之后的下 9 个文档)。但我不知道如何遍历集合并根据用户的得分值设置排名。任何人都可以帮忙吗?
编辑:分数越高,排名越高。因此,在该示例列表中,user2 是第一个(排名 1),user3 是第二个(排名 2),而 user1 的排名为 3。
Edit2:我正在使用猫鼬。有一些函数存在于原生 MongoDB 中,但不存在于 Mongoose 中。
好吧,我让它在猫鼬中工作。感谢 Astro 帮助我找到了正确的方向:
return this.model.find({}).sort({ score: -1 }).exec((err, docs) => {
for (var i = 0; i < docs.length; i++) {
this.model.update({ _id: docs[i].id }, { $set: { rank: i + 1 } }, { multi: true }).exec();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
924 次 |
最近记录: |