I'm new to node and mongodb and am trying to render a database query in a template, but I get the error that the property is undefined:
Cannot read property 'firstname' of undefined
Here's my index.js file:
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);
};
In the index.jade template, I've got:
#{currentUsers.firstname}
I've queried the database separately and know that there is a record:
> db.users.find()
{ "firstname" : "andy", "lastname" : "johnson", "email" : "andy@johnson.com", "_id" : ObjectId("51adf8a8c58996cf0c000001") }
Can anyone help me with what I'm doing wrong? I'm trying to pass the object to the template so that I can extract the data.
In your code, currentUsers is probably an API object (a Query or similar). In order to use the query's result, you need to use a callback:
exports.index = function(req, res){
db.users.find(function(err, currentUsers) {
res.render('index', {
currentUsers: currentUsers
});
});
};
Now you can use the currentUsers array from your Jade template:
#{currentUsers[0].firstName}