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

Node.js & JSON : Accessing object properties

本文关键字:访问 对象 属性 JSON js amp Node      更新时间:2023-09-26

我正在使用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并粘贴到fiddle),它会按预期工作。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] ] } ]

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

friends集合需要是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); 
    });
});