我想将我的集合(mongodb)中的所有条目显示为 html。
我之前已经做过一些基本的事情,例如......
router.get('/', function (req, res) {
res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid });
});
我给出的用户名
和成功
值用作html,以便在我的jade文件中我可以像这样显示它们......
body
p #{successful}
h1
|Welcome,
span #{username}
但现在我想循环遍历 mongodb 中特定集合中的所有条目,并通过我的 jade 文件显示它们。我怎样才能做到这一点?
最佳答案
您可以在 View 模板中使用迭代器来渲染集合中的所有元素。 为了获取该集合的所有元素,您需要在路由器内部定义一个查询(看看 mongoose )。 因此,您可以这样修改代码:
var Model = require('models/Model'); // this is your model schema
router.get('/', function (req, res) {
Model.find({}, function(err, result){
if(err)
return res.status(400).send(err);
// here were are passing to our view all the elements we got from out query
res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid, data: result });
});
});
现在我们可以在jade模板中定义迭代器了:
body
p #{successful}
h1
|Welcome,
span #{username}
ul
for element in data
li = element
这里我假设您使用jade作为模板引擎,mongodb作为数据库和mongoose .
关于javascript - 如何将集合中的所有条目显示为 html (node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172649/