Node.js& JSON:访问对象属性

时间:2015-10-28 15:28:21

标签: javascript json node.js bookshelf.js

我正在使用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] ] } ]

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

1 个答案:

答案 0 :(得分: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); 

    });
});