Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
Chadams Avatar asked Sep 04 '13 15:09

Chadams


1 Answers

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
};
like image 140
mikermcneil Avatar answered Jan 03 '23 18:01

mikermcneil