gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:15 24 4
gpt4 key购买 nike

我正在尝试从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com