如何将集合中的所有条目显示为html(node.js)

时间:2016-07-03 17:41:24

标签: javascript node.js mongodb pug

我想将我的集合中的所有条目(mongodb)显示为html。

我之前用基本的东西做过这个,例如......

router.get('/', function (req, res) {
    res.render('home', { title: 'Express', username: req.session.user, successful: req.query.valid });

});

我将usernamesuccessful值用作html,以便在我的jade文件中我可以像这样显示它们......

 body
   p #{successful}
   h1 
     |Welcome,
     span #{username}

但现在我想遍历mongodb中特定集合中的所有条目,并通过我的jade文件显示它们。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可以在视图模板中使用迭代器来渲染集合中的所有元素。 为了获得该集合的所有元素,您需要在路由器内部定义一个查询(看看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