Arrays NodeJS-如何从模块返回数组

Arrays NodeJS-如何从模块返回数组,arrays,node.js,module,export,return,Arrays,Node.js,Module,Export,Return,我有一个名为“userinfo.js”的模块,它从数据库中检索有关用户的信息。代码如下: 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

我有一个名为“userinfo.js”的模块,它从数据库中检索有关用户的信息。代码如下:

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;
        }
    });
});
}
从index.js(用于索引页面的控制器,我正试图从中访问userinfo)以如下方式:

var userinfo = require('../userinfo.js');

var profile = userinfo.getUserInfo(req.currentUser._id);
console.log(profile['username']);
节点返回给我这样一个错误:

console.log(profile['username']);   -->     TypeError: Cannot read property 'username' of undefined

我做错了什么?提前谢谢

您返回的是
profile['username']
而不是
profile
数组本身

您还可以返回
false
,因此在访问它之前应该检查
profile


编辑。再看一遍,return语句位于回调闭包中。因此,您的函数返回未定义。一种可能的解决方案(与节点的异步性质保持一致):

})); }


哦,对不起,这是我测试的错误。我已更正为返回配置文件;但仍然不起作用。错误是相同的:无法读取Undefinedy的属性“username”。返回语句位于回调闭包内。所以你的函数返回未定义-我已经更新了我的答案。它成功了,非常感谢。然而,根据这个示例,我被迫对回调使用异步编码样式,最好得到像var profile=userinfo.getUserInfo(req.currentUser.\u id)这样的smth;在主模块中。。。是否存在没有回调的变体?您应该始终在节点中使用async(正如您的DB api所做的那样),以保持主循环“空闲”以处理其他请求。如果您不介意阻止(比如在应用程序启动时),您可以搜索syncdbapi。否则,在包装异步库时,使用回调要容易得多(而且更好!)。
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);
        }
    });
    var userinfo = require('../userinfo.js');

    userinfo.getUserInfo(req.currentUser._id, function(err,profile){

      if(profile){
       console.log(profile['username']);
      }else{
       console.log(err);
      }
});