I’ve got a module called ‘userinfo.js’ retrieving info about users from DB. Here’s the code:
exports.getUserInfo = function(id){
db.collection("users", function (err, collection) {
var obj_id = BSON.ObjectID.createFromHexString(String(id));
collection.findOne({ _id: obj_id }, function (err, doc) {
if (doc) {
var profile = new Array();
profile['username']=doc.username;
return profile;
} else {
return false;
}
});
});
}
From index.js (controller for index page, from which I’m trying to access userinfo) in a such way:
var userinfo = require('../userinfo.js');
var profile = userinfo.getUserInfo(req.currentUser._id);
console.log(profile['username']);
Node returns me such an error:
console.log(profile['username']); --> TypeError: Cannot read property 'username' of undefined
What I’m doing wrong? Thanks in advance!
You’re returning
profile['username']not theprofilearray itself.Also you could return
false, so you should checkprofilebefore accessing it.EDIT. Looking over it again, your return statement is inside a callback closure. So your function is returning undefined. One possible solution, (keeping with node’s async nature):
});
}