2017-02-26 39 views
0

我有一點問題。JSON對象內的項目列表?

在我的MongoDB的收集,我有以下記錄:

{ 
    "_id" : ObjectId("58a77186e8b26df363d40195"), 
    "email" : "[email protected]", 
    "password" : "password123", 
    "fullName" : "Ola", 
    "interests" : ["football", "baseball"], 
    "__v" : 0 
} 


我想解析出 「利益」 雙組分,但是當我嘗試下面的代碼

var data = user; 
console.log(data.interests); 

。 ..我剛剛收到「未定義」。


當我嘗試到CONSOLE.LOG(數據)我收到:

{ __v: 0, 
    interests: [ "football", "baseball" ], 
    fullName: 'Ola', 
    password: 'password', 
    email: '[email protected]', 
    _id: 58a77186e8b26df363d40195 } 

是否有任何人誰可以看到這個問題?我真的很新鮮。我使用Node.js的

UPDATE
這是一個通過回調發送數據對象的功能:

try { 
    decoded = jwt.decode(token, config.secret); 

    User.findOne({ 
    email: decoded.email 
    }, function(err, user) { 
     if (err) throw err; 

     if (!user) { 
      callback(false); 
     } else { 
      callback(true, user); 
     } 
    }); 

    } catch (e) { 
    callback(false); 
    } 
+0

什麼,當你使用括號記號'的console.log情況(數據[ 「利益」])' –

+2

什麼的console.log的'輸出(數據[0])' –

+0

原因有兩個:要麼是'JSON字符串'而不是'JSON對象',要麼'你有'對象數組'而不是'直接'對象'。 –

回答

1

我看不出問題來了。我用你的obj來運行代碼它的工作正常(除了你從數據庫中獲得它,我直接分配,但那不是問題)。

var obj={ 
 
    "_id" : "58a77186e8b26df363d40195", 
 
    "email" : "[email protected]", 
 
    "password" : "password123", 
 
    "fullName" : "Ola", 
 
    "interests" : ["football", "baseball"], 
 
    "__v" : 0 
 
}; //I removed ObjectId() because of error: "message": "Uncaught ReferenceError: ObjectId is not defined", 
 
for(var k in obj) 
 
{ 
 
console.log(obj[k]); 
 
} 
 
//or directly doing it 
 
console.log(obj.interests);