Jeg synes, din metode er god, men skift bare results.length
til user.length
men hvis du vil bruge mongoDB-operation, gør sådan:
db.collection.aggregate([
{
"$sort": {
"score": -1
}
},
{
"$group": {
"_id": "",
"items": {
"$push": "$$ROOT"
}
}
},
{
"$unwind": {
"path": "$items",
"includeArrayIndex": "items.rank"
}
},
{
"$replaceRoot": {
"newRoot": "$items"
}
},
{
"$sort": {
"score": -1
}
}
])
du kan bruge lean()
og select
nogle felter i find
forespørgsel for at øge ydeevnen
async findRank() {
const users = await User.find({},"_id score").sort({score: -1}).lean()
for (let index = 0; index < users.length; index++) {
users[index].rank = index
}
return users
}
if you want group by the documents based on name or score ... it's better use mongodb operation