node.js - MongoDB - 获取排行榜前 5 个字段

标签 node.js mongodb express ejs

我有一个非常简单的表格,它将数据输出为

{
_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/

相关文章:

node.js - 如何将 Gatsby 与 NodeJs Express 后端集成

node.js - 将我的 node.js 应用上线

node.js - 主路由中的子路由没有获取静态文件 ExpressJS

java - 如何在 spring-context.xml 中设置属性

mongodb - 采用 NOSQL 方法时数据完整性的重要性?

express - Mocha + super 测试 + 断言 : print response body on test failure

javascript - 我可以使用具有多个源和多个目标的 Gulp 任务吗?

node.js - AWS EC2 上的 React 前端?

javascript - 插入mongodb中的一系列文件

javascript - Express js在React客户端中发送文件并下载