新增到nodejs。一直在努力解决这个基本问题。我在mongo db中有一些数据。我正在用ejs视图引擎快速使用。我可以看到来自console.log的mongo数据输出。我知道我可以使用以下标记在ejs模板中插入我的数据:<%= variable%>,但我似乎无法弄清楚如何在res.render代码中呈现它。将mongo数据渲染到ejs模板
下面是从蒙戈提取数据的代码:
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('car');
// Query the collection
collection.find(),(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found:', result);
} else {
console.log('No document(s) found with defined "find" criteria!');
}
//Close connection
db.close();
});
}
});
这是渲染部分:
// index page
app.get('/', function(req, res) {
res.render('pages/index', {collection: result});
});
这是EJS模板:
<h2>Cars:</h2>
<h3><%= result %>
这是我在浏览器中看到的错误:
ReferenceError:结果未定义
这是非常令人沮丧的,因为这应该是一个简单的直接前进...我试图做到这一点,而不使用猫鼬。
任何帮助将不胜感激。
谢谢。
谢谢。我已经将它更改为index.ejs中的<%= collection%>,但仍然得到ReferenceError:结果未定义... –
好的,我错过了您为回调添加的代码。我已经修改了我的app.js中的代码。我连接到数据库(如console.log输出所示),但浏览器挂在那里http:// localhost:8080,然后不连接... –
以下是集成了getResult回调函数的新代码: –