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

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

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

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

当前正在运行这个查询,它按降序返回我需要的特定数据:

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

上面的查询返回:

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

这是我想要的,但我无法单独标记每个值,返回数据但我无法对它做任何事情。

davidscofield 回答:使用 MongoDB/Mongoose 的数据库排行榜

您可以使用数组 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');
},'')
本文链接:https://www.f2er.com/6693.html

大家都在问