【问题标题】:How can I access my models in sailsjs outside a controller?如何在控制器外部访问我在sailsjs 中的模型?
【发布时间】:2013-09-04 15:19:28
【问题描述】:

我有一个看起来像这样的控制器。

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

    });
  }
};

但是,我宁愿不在控制器中进行所有这些登录,我宁愿将它们放在另一个模块中。

我的问题是,如何访问模型?他们是全球性的还是什么?

【问题讨论】:

  • 你试过var store = require(/path/to/models/store)吗?
  • @pdoherty926 也是一个非常有效的方法!

标签: node.js sails.js


【解决方案1】:

Chadams-- 模型默认是全局的。所以如果你做了sails generate model foo,你可以在你的代码中访问Foo。如果您不想以这种方式访问​​它们,您可以使用sails 引用来访问sails.models.foo,这是一样的。

希望有帮助!

顺便说一句,此自动全球化可通过自定义 sails.config.globals 来禁用。例如:

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

【讨论】:

  • ```module.exports = { readbyslug: function (req, res) {... 如果您尝试使用 Store 或sails.models.store OUTSIDE module.exports 或外部函数 (req, res) 你会得到未定义的
  • 我为迁移创建了自定义目录app/api/migrations,但我无法访问它。 sails not defined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 2017-10-06
相关资源
最近更新 更多