【发布时间】:2016-03-01 05:39:55
【问题描述】:
nodejs 新手。一直在努力解决这个基本问题。我在 mongo 数据库中有一些数据。我正在使用带有 ejs 视图引擎的 express。我可以看到来自 console.log 的 mongo 数据输出。而且我知道我可以使用以下标签将我的数据插入到 ejs 模板中:,但我似乎无法弄清楚如何在 res.render 代码中呈现它。
这是从 mongo 中提取数据的代码:
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: 结果未定义
这非常令人沮丧,因为这应该是一个简单的直接...我正在尝试不使用猫鼬来做到这一点。
任何帮助将不胜感激。
谢谢。
【问题讨论】: