来自数据库的排行榜使用 MongoDB/Mongoose

Leaderboard from database using MongoDB/Mongoose

在每个文档中都有一个带有数字值的级别字段和一个带有字符串值的 twitch_username。我想 return 这些值是这样的:

1. Twitch: <twitch_username> Level: <level>
2. Twitch: <twitch_username> Level: <level>
3. Twitch: <twitch_username> Level: <level>
//...

我尝试通过数据映射、运行 for 循环、将数据推入新数组等,但我似乎无法理解它。

目前运行这个查询return我需要的具体数据降序排列:

  User.find({}).select('twitch_username level -_id').sort({level: 'desc'}).exec((err,docs) => { 
      // console.log(docs);
  });

上面的查询 returns:

[
  { twitch_username: 'user1', level: 67 },
  { twitch_username: 'user2', level: 14 }
]

这正是我想要的,但我不能单独标记每个值,数据是 returned 但我不能用它做任何事情。

您可以使用 array reduce 将其缩减为字符串

const output = [
  { twitch_username: 'user1', level: 67 },
  { twitch_username: 'user2', level: 14 }
];

然后使用reduce函数

output.reduce((final, current, id) => {
    return (final + (id+1) + '. Twitch: ' + current.twitch_username + ' Level: ' + current.level + '\n');
}, '')