0

In a NodeJS/Knex/Bookshelf app I'm helping to rewrite, I'm doing a withRelated query on User model for messages and interests:

  return User.query({where: {id: user.id}})
      .fetch({withRelated: ['messages', 'interests']}).then(function(user) {
        return {
          id: user.id,
          prop1: user.related('messages'),
          prop2: user.related('interests'),
        };
      });

But it's returning back CollectionBases:

{ id: 1,
  messages: 
    CollectionBase {
     model: { ... }
    }
   }
  interests:
    CollectionBase {
     model: { ... }
    }
  }

But I need it to return the actual arrays of data objects:

{ id: 4068,
  messages: 
   [ { id: 2,
       title: 'Customer',
       _pivot_user_id: '1',
       _pivot_user_role_id: '2' } ],
  interests: 
   [ { id: 86,
       name: 'interest1',
       _pivot_user_id: '4068',
       _pivot_org_id: '86' } ] }

If I try to JSON'ify it, I get error:

user.toJSON is not a function

var user = {
  id: user.id,
  prop1: user.related('messages'),
  prop2: user.related('interests'),
};
return user.toJSON();

How do I return the array of objects per related objects for User?

user3871
  • 12,432
  • 33
  • 128
  • 268

1 Answers1

1

Instead of:

return user.toJSON();

try doing:

return JSON.stringify(user);

if you really want JSON, or this:

var user = {
  id: user.id,
  prop1: user.related('messages').toJSON(),
  prop2: user.related('interests').toJSON(),
};

if you want a JS object that would look like before serializing to JSON.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • rsp thanks for this- even from reading http://stackoverflow.com/questions/20734894/difference-between-tojson-and-json-stringify I don't understand why json stringify works, but toJSON doesn't – user3871 Mar 13 '17 at 17:04
  • @Growler `JSON.stringify()` if a method on the global `JSON` object that is also available so the method is also always available. the `.toJSON()` method is a method of a given object, like the object returned by `user.related('messages')` in your example but this is the object than must have that method and not every object does. Try: `var x = 123; JSON.stringify(x);` and then `var x = 123; x.toJSON();` Here `x` doesn't have that method so you cannot call it. – rsp Mar 15 '17 at 13:45