2016-12-14 65 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){ 
相关问题