2012-07-28 32 views
0

我有一個名爲'userinfo.js'的模塊從DB獲取關於用戶的信息。下面的代碼:NodeJS - 如何從模塊返回數組

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(控制器索引頁面,從中我試圖訪問用戶信息)以這樣的方式:

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 

我做錯了什麼?提前致謝!

回答

9

你回來了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); 
     } 
    }); 

}); }

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

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

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

哦對不起,這是我的測試錯誤。我已更正以返回配置文件;仍然不起作用。 – f1nn 2012-07-28 22:46:03

+0

錯誤是一樣的:無法讀取未定義的屬性「用戶名」 – f1nn 2012-07-28 22:46:46

+0

您的return語句在回調閉包內。所以你的函數返回undefined-我已經更新了我的答案。 – spacious 2012-07-28 22:58:25