Reputation: 1222
I have getUsers() in Users controller like below
getUsers: function(req, res){
var results = User.getUsers();
return res.send(results);
}
I'm calling User Model's getUsers() method. Code for this method is below
getUsers: function(){
User.find({}).exec(function findCB(err, found){
return found;
});
}
Now how do I get this result(in this case 'found') back in the controller? So that I can send it to the front-end using response object.
It seems like these function calls are asynchronous..
Upvotes: 1
Views: 1634
Reputation: 6770
Your controller would like as :
getUsers: function(req, res){
User.getUsers(function (results) {
res.json(results);
});
}
And model will be as :
getUsers: function(cb){
User.find({}).exec(function(err, found){
if(err) // your error handling code
cb(found);
});
}
cb is the callback function
Upvotes: 1
Reputation: 5979
Is there a reason you are creating the extra method inside your model. You can just access all users directly.
getUsers: function(req, res){
User.find().exec(function(results){
return res.ok(results);
})
}
Upvotes: 0