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

标签 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 });

});

我给出的用户名成功值用作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/

相关文章:

javascript - node.js http服务器如何获取连接数

javascript - 只从 node.js 中的套接字读取前 N 个字节

java - "or"嵌入文档java中的条件

angularjs - 看起来您正尝试在 native 驱动程序端口上通过 HTTP 访问 MongoDB

javascript - 从 Node.js 将文件插入 MongoDB 时出错

node.js - 错误 : grid. mongodb.GridStore 不是构造函数,使用 mongoose、Grid-fs-stream 和 grid multer 存储

javascript - 如何从 require.js 错误中获取行号?

javascript - 更改 Windows 中的文本选择方法

javascript - 从没有页面刷新的模式异步 Ajax 保存 Laravel 5.2

javascript - 如何配置 webpack 3.5.4 只为 JS 创建源映射,并跳过 CSS?