0

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?

vromanch
  • 939
  • 10
  • 22

1 Answers1

5

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?

Community
  • 1
  • 1
ataman
  • 2,644
  • 17
  • 22
  • A bit of a stretch commenting on a year-old answer, but what would you recommend as the "different place" for doing the data queries? I have a [similar situation here](http://stackoverflow.com/questions/30164255/sails-js-waterline-executing-waterline-queries-in-tojson-function-of-a-model/30164591#30164591) and can't wrap my head around what I should do. – Fissio May 11 '15 at 10:28