Sails.js模型中的CRUD

时间:2014-09-02 18:39:55

标签: node.js sails.js crud waterline

我使用命令" sails generate model"创建了一个Sails.js模型。该模型生成如下:

module.exports = {
  connection: 'someMysqlServer',
  attributes: {
    amount : { type: 'float' },
    country : { type: 'string' },
    month : { type: 'string' }
  }
};

我正在尝试使用此模型实例的 .create()函数,如下所示,但我收到错误:

var myModel = require ('../models/Info') ;
module.exports = {
getInfo: function (req, res) {
      console.log("inside getInfo controller");
      myModel.create({amount:3.5 , country:'spain' , month: 'january' }) ;
  } ,
}

使用 .create()功能时,我收到以下错误:

error: Sending 500 ("Server Error") response: 
 TypeError: Object #<Object> has no method 'create'
    at module.exports.getInfo (/vagrant_data/inputinterface/b2bInputInterface/api/controllers/InputPageController.js:38:26)
    at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:178:5)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
    at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:135:11)
    at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
    at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
    at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
    at /usr/lib/node_modules/sails/lib/router/bind.js:186:7
    at alwaysAllow (/usr/lib/node_modules/sails/lib/hooks/policies/index.js:209:11) [TypeError: Object #<Object> has no method 'create']

根据以下http://sailsjs.org/#/documentation/reference/waterline/models/create.html 这个方法应该可以自动访问吗?

1 个答案:

答案 0 :(得分:1)

Sails为您全球化模型;没有必要自己尝试require()它们,也不会按预期工作。

如果您的模型文件位于 api / models / Info.js 中,那么您的控制器将如下所示:

module.exports = {
  getInfo: function (req, res) {
    Info.create({amount:3.5 , country:'spain' , month: 'january' });
  }
}

在创建Sails应用程序时,您不必尝试遵循Waterline文档,而是在Sails docs for models之后获得更多运气。