【问题标题】:Item-list inside of a JSON-object?JSON对象内的项目列表?
【发布时间】:2017-02-26 02:43:38
【问题描述】:

我有一个小问题。

在我的 MongoDB 集合中,我有以下记录:

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


我想解析出“兴趣”部分,但是当我尝试以下代码时

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

...我只收到“未定义”。


当我尝试 console.log(data) 我收到:

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

有没有人能看出问题?我对此真的很陌生。我正在使用 Node.JS

更新
这是通过回调发送数据对象的函数:

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

【问题讨论】:

  • 使用括号符号console.log(data["interests"])会发生什么
  • console.log(data[0])的输出是什么
  • 两个原因:要么你有JSON string而不是JSON Object,要么你有array of object而不是直接object
  • 能否提供一个代码,用于从数据库中检索记录并记录它?
  • 感谢回复!

标签: arrays json node.js mongodb express


【解决方案1】:

我看不出问题出在哪里。我使用你的 obj 来运行代码,它工作正常(除了你是从数据库中获取它,我是直接分配的,但这不是问题)。

var obj={
    "_id" : "58a77186e8b26df363d40195",
    "email" : "mail@mail.com",
    "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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-06
    • 2021-05-04
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多