C.P.
C.P.

Reputation: 1222

How to send data back to controller from model in Sails.js

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

Answers (2)

Abhay
Abhay

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

  • And yes "Fat model, skinny controller", is the good approach when following MVC

Upvotes: 1

Meeker
Meeker

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

Related Questions