3

I have a node.js method that using mongoose in order to return some data, the problem is that since I'm using a callback inside my method nothing is being returned to the client

my code is:

var getApps = function(searchParam){
    var appsInCategory = Model.find({ categories: searchParam});
    appsInCategory.exec(function (err, apps) {
        return apps;
    });
}

If I'm trying to do it synchronously by using a json object for example it will work:

var getApps = function(searchParam){
    var appsInCategory = JSONOBJECT;
    return appsInCategory
} 

What can I do?

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161

1 Answers1

5

You can't return from a callback - see this canonical about the fundamental problem. Since you're working with Mongoose you can return a promise for it though:

var getApps = function(searchParam){
    var appsInCategory = Model.find({ categories: searchParam});
    return appsInCategory.exec().then(function (apps) {
        return apps; // can drop the `then` here
    });
}

Which would let you do:

getApps().then(function(result){
    // handle result here
});
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504