f1n*_*1nn 0 arrays module export return node.js
我有一个名为'userinfo.js'的模块,用于从DB中检索有关用户的信息.这是代码:
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;
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
从index.js(索引页的控制器,我试图访问userinfo)以这种方式:
var userinfo = require('../userinfo.js');
var profile = userinfo.getUserInfo(req.currentUser._id);
console.log(profile['username']);
Run Code Online (Sandbox Code Playgroud)
Node返回我这样的错误:
console.log(profile['username']); --> TypeError: Cannot read property 'username' of undefined
Run Code Online (Sandbox Code Playgroud)
我做错了什么?提前致谢!
你返回的profile['username']不是profile数组本身.
您也可以返回false,因此您应该profile在访问之前进行检查.
编辑.再看一遍,你的return语句在回调闭包内.所以你的函数返回undefined.一种可能的解决方案,(保持节点的异步性质):
exports.getUserInfo = function(id,cb){
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;
cb(err,profile);
} else {
cb(err,null);
}
});
Run Code Online (Sandbox Code Playgroud)
}); }
var userinfo = require('../userinfo.js');
userinfo.getUserInfo(req.currentUser._id, function(err,profile){
if(profile){
console.log(profile['username']);
}else{
console.log(err);
}
});
Run Code Online (Sandbox Code Playgroud)