Reputation: 989
I have TopPlayer model:
module.exports = {
attributes: {
league_id: 'number',
playerid: 'number',
playerimage: 'url',
teamimage:'url',
teamname:'string',
season: 'string',
player: 'string',
assets: 'number',
goals: 'number',
toJSON: function() {
var obj = this.toObject();
Player.findOne({gs_id:obj.playerid}).done(function(err, player) {
obj.playerImage = player.image;
console(player.image);// everything is ok
return obj; // but this is returning null
});
}
}
};
and toJSON return null objects always. Player is founded when i debug, but obj instance inside callback is null, and i cant return him :( How can i resolve problem like this?
Upvotes: 0
Views: 604
Reputation: 2664
In your case toJSON
returns nothing because you actually don't return anything from it. Look at my comment:
toJSON: function() {
var obj = this.toObject();
Player.findOne({gs_id:obj.playerid}).done(function(err, player) {
obj.playerImage = player.image;
console(player.image);// everything is ok
return obj; // but this is returning null
});
// You must return a value here:
return ojb;
}
You can't write toJSON
method in async way. It must return a value. This method is intended for simple tasks, such as filtering of output. If you want to do complex things, such as data queries, consider to do it in different place.
For clarification why what you are doing is impossible, refer to one of the many similar questions on SO, for example: How to return value from an asynchronous callback function?
Upvotes: 5