2017-02-26 38 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);