Reputation: 12708
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?
Upvotes: 0
Views: 1046
Reputation: 111306
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.
Upvotes: 1