Sails.js return object from service undefined when using search query

I created a service called AppService. Its getUserPostionOptions function should return an object:

getUserPostionOptions: function (user) {
   // PositionOptions.findOne({id:'53f218deed17760200778cfe'}).exec(function (err, positionOptions) {
        var positionDirectionsOptions = [1,2,3];
        var positionLengthsOptions = [4,5,6];
        var object = {
            directions:positionDirectionsOptions, 
            lengths:positionLengthsOptions
        };   
        return object;
  // });
}

      

This works, in my controller position the Options is populated correctly:

var positionOptions = AppService.getUserPostionOptions(user);

      

However, when I uncomment the search query, the item is found, but the object is returning undefined.

Thanks in advance for your help

+3


source to share


1 answer


SailsJs ORM (and almost NodeJs database query methods) uses a blocking mechanism with a callback function. Therefore, you need to change your code to:

getUserPostionOptions: function (user, callback) {
  PositionOptions.findOne({id:'53f218deed17760200778cfe'}).exec(function (err, positionOptions) {
    var positionDirectionsOptions = [1,2,3];
    var positionLengthsOptions = [4,5,6];
    var object = {
        directions:positionDirectionsOptions, 
        lengths:positionLengthsOptions
    };   
    callback(null, object); // null indicates that your method has no error
  });
}

      



Then just use it:

AppService.getUserPostionOptions(user, function(err, options) {
  if (!err) {
    sails.log.info("Here is your received data:");
    sails.log.info(options);
  }
});

      

+5


source







All Articles