Danial
Danial

Reputation: 703

CRUD in Sails.js model

I have created a Sails.js Model by using command "sails generate model". The model is generated as follows:

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

I am trying to use .create() function of an instance of this model , inside a controller as follow , but I receive error :

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' }) ;
  } ,
}

I receive the following error while using .create() function :

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']

According to the following http://sailsjs.org/#/documentation/reference/waterline/models/create.html this method should be accessible automatically ?

Upvotes: 0

Views: 4671

Answers (1)

sgress454
sgress454

Reputation: 24948

Models are globalized for you by Sails; there is no need to attempt to require() them on your own nor will this work as intended.

If your model file lives in api/models/Info.js, then your controller would look something like:

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

Rather than trying to follow the Waterline docs when creating a Sails app, you'll have a lot more luck following the Sails docs for models.

Upvotes: 1

Related Questions