Chadams
Chadams

Reputation: 1933

How can I access my models in sailsjs outside a controller?

I have a controller that looks like this.

module.exports = {

    readbyslug: function (req, res) {
    var slug = req.param('id');
    Store.findOneByName(slug.split('-').join(' '))
      .then(function(err, store){
      if(err)
        res.send({status:'error', msg:'no store'});
      res.send(store);

    });
  }
};

however, I would rather not have all this login in the controllers, I would rather stick them in another module.

My question is, how do I access the models? are they global or something?

Upvotes: 5

Views: 7035

Answers (1)

mikermcneil
mikermcneil

Reputation: 11271

Chadams-- models are global by default. So if you did sails generate model foo, you could access Foo in your code. If you'd rather not access them that way, you can use the sails reference to access sails.models.foo, which is the same thing.

Hope that helps!

btw this auto-globalization is disable-able by customizing sails.config.globals. For example:

// To configure what's available globally, make a new file, `config/globals.js`
// with the following contents:

// In this example, I'll disable globalization of models, as well as _ and async.
// (But I'll leave the `sails` global available.)

// Variables which will be made globally accessible to the server process
module.exports.globals = {
  _ : false,
  async: false,
  models: false,
  sails: true
};

Upvotes: 17

Related Questions