【问题标题】:retrieving data from mongodb in jade template在玉模板中从 mongodb 中检索数据
【发布时间】:2013-06-04 14:52:26
【问题描述】:

我是 node 和 mongodb 的新手,正在尝试在模板中呈现数据库查询,但我收到属性未定义的错误:

Cannot read property 'firstname' of undefined

这是我的 index.js 文件:

var dburl = 'localhost/olpdb';


var collections = ['users'];


var db = require('mongojs').connect(dburl, collections);

var currentUsers = db.users.find();

exports.index = function(req, res){
  res.render('index', currentUsers);
};

在 index.jade 模板中,我有:

#{currentUsers.firstname}

我已经单独查询过数据库,知道有记录:

> db.users.find()
{ "firstname" : "andy", "lastname" : "johnson", "email" : "andy@johnson.com", "_id" : ObjectId("51adf8a8c58996cf0c000001") }

谁能帮我解决我做错了什么?我正在尝试将对象传递给模板,以便提取数据。

【问题讨论】:

    标签: node.js mongodb pug


    【解决方案1】:

    在您的代码中,currentUsers 可能是一个 API 对象(查询或类似对象)。为了使用查询的结果,您需要使用回调:

    exports.index = function(req, res){
      db.users.find(function(err, currentUsers) {
        res.render('index', {
          currentUsers: currentUsers
        });
      });
    };
    

    现在您可以使用 Jade 模板中的 currentUsers 数组

    #{currentUsers[0].firstName}
    

    【讨论】:

    • 这给了我错误:无法读取属性 'firstname' of null
    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 2018-05-03
    • 2015-04-15
    • 2016-09-08
    • 1970-01-01
    • 2016-12-20
    • 2022-12-24
    • 2015-08-20
    相关资源
    最近更新 更多