【问题标题】:Node.js & JSON : Accessing object propertiesNode.js 和 JSON:访问对象属性
【发布时间】:2015-10-28 15:28:20
【问题描述】:

我正在使用 ExpressJS、NodeJS 和 Bookshelf.js

我正在尝试查看用户的朋友列表,但如果我想访问对象的属性,则会收到 "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" 错误,如下所示:friends[0].friends[0].email

router.get('/relative', function (req, res) {
    user.where('id', 1).fetchAll({withRelated: ['friends']}).then(function (friends) {
        //res.send(friends);
        res.json(friends); // works
        res.send(friends[0].friends[0].email); // throws error

    });
});

如果我在客户端尝试相同的 JSON 对象(只是手动复制返回的 json 并粘贴到小提琴中),它会按预期工作。 jsfiddle 在下面。

http://jsfiddle.net/tmrd/zjzs4etu

我做错了什么?

虽然 res.send(friends) 在上面给出了一个 JSON 对象,但 console.log(friends) 会返回这个:

CollectionBase {
  model:
   { [Function]
     NotFoundError: [Function: ErrorCtor],
     NoRowsUpdatedError: [Function: ErrorCtor],
     NoRowsDeletedError: [Function: ErrorCtor] },
  length: 1,
  models:
   [ ModelBase {
       attributes: [Object],
       _previousAttributes: [Object],
       changed: {},
       relations: [Object],
       cid: 'c2',
       id: 1 } ],
  _byId:
   { '1':
      ModelBase {
        attributes: [Object],
        _previousAttributes: [Object],
        changed: {},
        relations: [Object],
        cid: 'c2',
        id: 1 },
     c2:
      ModelBase {
        attributes: [Object],
        _previousAttributes: [Object],
        changed: {},
        relations: [Object],
        cid: 'c2',
        id: 1 } },
  _knex: null,
  _events: {},
  _eventsCount: 0 }

编辑 2

[ { id: 1,
    email: 'user1@gmail.com',
    username: 'user1',
    password_hash: '',
    image_id: null,
    name: '',
    is_public: 0,
    language_id: null,
    notification_quote: 1,
    phone: '',
    notify_sms_password_change: 0,
    notify_sms_diff_country_login: 0,
    notify_sms_unusual_activity: 0,
    search_engine_visibility: 0,
    allowed_senders: 1,
    use_ssl: 0,
    notify_mail_friendship_request: 1,
    notify_mail_comment_on_my_status: 1,
    notify_mail_comment_on_my_photo: 1,
    notify_mail_birthdays: 1,
    notify_mail_app_game_request: 1,
    invite_number_of_people: '0',
    sms_login: 0,
    notify_sms_different_ip: 0,
    allowed_friendship_requests: 1,
    email_key: '',
    points: 0,
    confirmation_code: '',
    confirmed: 0,
    status: 1,
    deleted_at: '0000-00-00 00:00:00',
    cover_image_id: null,
    updated_at: '0000-00-00 00:00:00',
    created_at: '0000-00-00 00:00:00',
    type: 0,
    friends: [ [Object], [Object] ] } ]

编辑:我将从查询中排除敏感列,以便它们在生产中不可见,这只是举例。

【问题讨论】:

  • 我认为你需要调用的是res.send(friends[0].email);
  • 使用user.where(),您可能会得到单个项目而不是列表。试试res.send(friends.friends[0].email)
  • @Angad,不起作用。 @Safari,我收到 Unhandled rejection TypeError: Cannot read property '0' of undefined 错误。
  • 能否请教console.log(朋友)
  • 我按照你的要求做了,请看编辑。

标签: javascript json node.js bookshelf.js


【解决方案1】:

好友集合需要是json字符串才能发送。

router.get('/relative', function (req, res) {
    user.where('id', 1).fetchAll({withRelated: ['friends']}).then(function (friends) {
        //res.send(friends);
        friends = friends.toJSON();
        res.json(friends); // res.json automatically calls the toJSON method if the function is no json
        res.send(friends[0].friends[0].email); 

    });
});

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2011-11-05
    相关资源
    最近更新 更多