Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sails.js the return object from service is undefined when using a find query

I created a service called AppService. Its function getUserPostionOptions is supposed to 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 positionOptions gets populated correctly:

var positionOptions = AppService.getUserPostionOptions(user);

However, when I uncomment the find query the item is found but the object returns undefined.

Thank in advance for your help

like image 620
tomasso Avatar asked Dec 07 '25 19:12

tomasso


1 Answers

SailsJs ORM (and almost NodeJs database querying methods) uses non-blocking mechanism via callback function. So you have to change your code into:

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);
  }
});
like image 199
haotang Avatar answered Dec 11 '25 09:12

haotang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!