我有一个非常简单的表格,它将数据输出为
{
_id: 55dbdffeaba8ee274d3b9f89,
firstname: 'Jim',
lastname: 'Kirk',
email: 'ewrwe@kewoio.com',
points: 3333,
}
到目前为止,我的数据库中有大约 10 条记录。我使用以下变量来创建用户模型。
var User = mongoose.model('User', userSchema);
我想对点进行排序,并在任何给定时间显示前 5 个点。将其存储为变量并作为数组传递到express/ejs。
到目前为止,我有这个查询,但是当我 console.log 时,我得到了未定义。
var leaderboard = User.find( {points: {$exists: true}} ).sort({points : -1}).limit(5);
更新:在 Robomongo 中运行此查询后,我获得了包含所有数据的 5 条记录,但 console.log 返回数据“未定义”。如何将数据作为数组输出以放入表中并过滤掉 _id 和电子邮件?
最佳答案
问题发生在
之后var leaderboard = User.find( {points: {$exists: true}} ).sort({points : -1}).limit(5);
get执行的排行榜包含一个光标。将 .toArray()
附加到命令末尾,您就可以开始了。您的最终命令应如下所示:
var leaderboard = User.find( {points: {$exists: true}} ).sort({points : -1}).limit(5).toArray();
查看the documentation了解更多信息。
关于node.js - MongoDB - 获取排行榜前 5 个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32213174/