2016-12-14 20 views
0

私はかなりjavascriptに新しく、現在はアプリケーション開発にMEANスタックを使用しています。未処理の約束拒否:TypeError:未定義の 'username'プロパティを読み取ることができません

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); 

     }); 

    }); 
} 

そしてそれは常にエラーを返す:私は、特定のユーザーの友人のIDとユーザー名をユーザー名を検索するには、次のコードを使用し

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

この問題で任意の助けを大幅に高く評価されます!

編集:

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); 

      }); 

     }); 


}); 

とコンソールログには、次のとおりです:ERRログを取得するために従うよう 私は、コードを変更し

{ 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.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){ 

あなたはuserList.findOneが有効な 'currUser'を返していることを確認していますか? – faboolous

+0

はい、その部分が有効なcurrUserを返します。 – user3125530

+2

'TypeError:プロパティ 'username'がundefinedの場合、コードは' undefined'オブジェクトから 'username'プロパティにアクセスしています。 currUserが定義されていない場合、これはあなたの 'currUser.username'にあります。 – faboolous

答えて

0

ちょうどその時でのtoArrayを交換してください。

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