简体   繁体   中英

Node.js & JSON : Accessing object properties

I'm using ExpressJS, NodeJS and Bookshelf.js

I'm trying to view a list of friends of a user, but I get "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" error if I want to access a property of the object, like the following: 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

    });
});

If I try the same JSON object in client side (just copied the returned json manually and pasted to a fiddle), it works as expected. jsfiddle is below.

http://jsfiddle.net/tmrd/zjzs4etu

What I am doing wrong?

While res.send(friends) gives a JSON object above, console.log(friends) returns this :

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 }

Edit 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] ] } ]

Edit : I'll exclude sensitive columns from the query so they'll be invisible in production, this is just to give an example.

the friends collection needs to be a json string before you can send it.

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

    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM