Tôi nghĩ rằng phương pháp của bạn là tốt nhưng chỉ cần thay đổi results.length thành user.length nhưng nếu bạn muốn sử dụng thao tác mongoDB, hãy làm như thế này:
db.collection.aggregate([
{
"$sort": {
"score": -1
}
},
{
"$group": {
"_id": "",
"items": {
"$push": "$$ROOT"
}
}
},
{
"$unwind": {
"path": "$items",
"includeArrayIndex": "items.rank"
}
},
{
"$replaceRoot": {
"newRoot": "$items"
}
},
{
"$sort": {
"score": -1
}
}
])
bạn có thể sử dụng lean() và select một số trường trong find truy vấn để tăng hiệu suất
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