从玉模板中的mongodb中检索数据
我是新来的节点和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}
我已经单独查询数据库,知道有一个logging:
> db.users.find() { "firstname" : "andy", "lastname" : "johnson", "email" : "andy@johnson.com", "_id" : ObjectId("51adf8a8c58996cf0c000001") }
任何人都可以帮我做我做错了什么? 我试图将对象传递给模板,以便我可以提取数据。
在你的代码中, currentUsers
可能是一个API对象(一个查询或类似的)。 为了使用查询的结果,你需要使用callback:
exports.index = function(req, res){ db.users.find(function(err, currentUsers) { res.render('index', { currentUsers: currentUsers }); }); };
现在,您可以使用Jade模板中的currentUsers
数组 :
#{currentUsers[0].firstName}