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

做~自己de王妃 提交于 2019-12-22 08:37:22

问题


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?


回答1:


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
};


来源:https://stackoverflow.com/questions/18617716/how-can-i-access-my-models-in-sailsjs-outside-a-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!