Monday, 13 March 2017

knex with related returns collection bases

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?



via Growler

No comments:

Post a Comment