2016-12-14 41 views
0

我對JavaScript很新穎,目前我正在使用MEAN堆棧來開發應用程序。我用下面的代碼來找到用戶名,朋友的ID和用戶名特定用戶的:未處理的承諾拒絕:TypeError:無法讀取未定義的屬性「用戶名」

router.get('/init', function(req, res) { 

    var db = req.db; 
    var userList = db.get('userList'); 

    //get username & friends 
    userList.findOne({ "_id" : ObjectId("584d576ef0000ef5a94706f5") },{ fields: { "username": true, "_id": false, "friends":true } }, function(err, currUser){ 

     userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){ 

      // Generate response 

      var response = { 

       "username": currUser.username, 
       "friends": friendList 
      }; 

      res.json(response); 

     }); 

    }); 
} 

,它總是返回錯誤:

(node:6044) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'friends' of undefined 

在這個問題上的任何幫助,非常感謝!

編輯: 我改變了代碼如下得到ERR日誌:

router.get('/init', function(req, res) { 

    var db = req.db; 
    var userList = db.get('userList'); 

     //var username, friends; 
     userList.findOne({ "_id" : ObjectId("584d576ef0000ef5a94706f5") },{ fields: { "username": true, "_id": false, "friends":true } }, function(err, currUser){ 

      console.log(currUser); 
      if(err) console.log("findOne: "+err); 

      userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){ 

       // Generate response 

       if(err) console.log("find: "+err); 

       var response = { 

        "username": currUser.username, 
        "friends": friendList 
       }; 

       res.json(response); 

      }); 

     }); 


}); 

和控制檯日誌:

{ username: 'Eddie', friends: [ 'Ken', 'Alice', 'Bill' ] } 
undefined 
findOne: TypeError: userList.find(...).toArray is not a function 
(node:8888) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'friends' of undefined 
+0

你確定userList.findOne返回一個有效的'currUser'? – faboolous

+0

是的那個部分返回一個有效的currUser。 – user3125530

+2

'TypeError:無法讀取undefined'的屬性'username',表示代碼正在從一個未定義的對象訪問屬性'username'。這可能在你的'currUser.username'這種情況下,如果currUser會被undefined – faboolous

回答

0

只是然後更換指定者。

userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){ 

userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).then(function(err, friendList){ 
相關問題