4

I have user model and user Controller that I have generate from sails command. I just want call function that I created on model from controller like:

// user model

module.exports = {
  attributes: {
     name: {
       type: 'string',
       required: true
     }
  },
 CallUserFunction: function(){
   //some code goes here.
 }
}

// userController

module.exports = {
   create: function(req, res){
      User.CallUserFunction();//can i call function in user Model like this? 
  }
}
user2938465
  • 81
  • 1
  • 5
  • possible duplicate of [How to define instance methods for models with sails.js](http://stackoverflow.com/questions/17720846/how-to-define-instance-methods-for-models-with-sails-js) – bredikhin Jan 28 '14 at 15:36
  • If your question is, "can I defined a class method in my model", then the answer is "yes". Have you tried it? – sgress454 Jan 28 '14 at 18:43

1 Answers1

2

What you're trying to do isn't an instance method. Instead of calling just User.CallUserFunction() you need to do something like this:

User Model

module.exports = {
  attributes: {
     name: {
       type: 'string',
       required: true
     }
  },
 CallUserFunction: function(){
   //some code goes here.
 }
}

User Controller

module.exports = {
   create: function(req, res){
      sails.models.user.CallUserFunction();//can i call function in user Model like this? 
  }
}

edit: forgive any typo's as i'm not in front of my dev workstation to test this, i do know its very close to that syntax of sails.models though.

NDBoost
  • 10,184
  • 6
  • 53
  • 73
  • Hi @gorelative but how can I have a returned value from MyUsers.myCollectionMethod(); when I call this from a Controller like var tmpResult = MyUsers.myCollectionMethod(); – alexventuraio May 09 '16 at 18:54