2013-06-04 81 views
2

我是新来的节点和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" : "[email protected]", "_id" : ObjectId("51adf8a8c58996cf0c000001") } 

任何人都可以帮助我做我做错了什么?我试图将对象传递给模板,以便我可以提取数据。

回答

0

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

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

现在你可以使用currentUsers阵列从玉模板:

#{currentUsers[0].firstName} 
+0

这给我的错误:无法读取property'firstname'null – babbaggeii

+0

更正了代码中的拼写错误。 – rvidal

+0

非常完美,非常感谢 – babbaggeii