node.js - 查询 mongodb 并尝试将结果显示在 index.pug 中,获取 [object Object]

标签 node.js mongodb

我正在尝试从 pug/html 页面中的 mongodb 获取数据,我已经接近但还没有完全实现。我已经运行了相关的 Node 和 mongo 服务器。

我得到的示例数据是

[ { _id: 59708077c9412f6d7f7e8485,
username: 'xyz123',
email: 'xyz123@test.com' } ]

当我控制台记录它时,它会出现在 Node 终端窗口上。

我的app.js中的代码是

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/questiondb';

var mongotest = [];

MongoClient.connect(url, function (err, db) {
        var str = db.collection('usercollection').find();
        str.each(function (err, doc) {
                mongotest.push(doc); //Push result onto results_array
                                console.log(mongotest)

        });

                app.get('/', (req, res) => {
                    res.render('index', {"results": mongotest });


                });

            });

在我的index.pug文件中我有

  p Hello
    each mongotest, i in results
      div Result #{i} #{mongotest}

html页面的结果是

Result [object Object]

我假设我必须将结果从对象更改为字符串。当我使用 JSON.stringify 之类的东西时,我通过 pug 中的循环将查询中的每个单独字母呈现为单独的迭代。

我已经很接近了,但我的学习中显然存在一个漏洞:-)

提前致谢

已修复

对于那些想知道的人,这些是我对代码所做的更改以使其正常工作。我将该属性保存到一个变量中,并在哈巴狗模板中引用该属性。

var readVar;
                readVar = mongotest[0].username;

    });
};

            app.get('/', (req, res) => {
                res.render('index', { readVar});

最佳答案

.find() 方法是异步方法。 你应该像这样使用它:

db.collection('usercollection').find({}, callback);

function callback(err, docs){
    if(err) { /*errorHandler*/ };
    docs.each(function (err, doc) {
        if(err) { /*errorHandler*/ }
        mongotest.push(doc); //Push result onto results_array
        console.log(mongotest)
    });
};

不要忘记处理回调中的错误

关于node.js - 查询 mongodb 并尝试将结果显示在 index.pug 中,获取 [object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212475/

相关文章:

javascript - 使用 CommonJS 模块汇总将未命名函数导出为模块?

javascript - 我可以在 mongo 查询中索引对象吗?

javascript - 指向 Express 路线的动态表单操作

node.js - Node 错误 : read ECONNRESET

node.js - Google 网络字体在 Express 中不起作用

node.js - 在流式 HTTP 客户端之间共享 DEFLATE 压缩的数据 block

javascript - Mongodb递归搜索

node.js - 使用 switch case 更新集合中的多个文档

python - PyMongo insert_one 异常/错误处理

mongodb - 用于多个集合 MongoDB 的 Morphia Single dao