Vikas Kumar Vikas Kumar - 18 days ago 6
Node.js Question

How to use .create() function in sails.js?

I've read the documentation of sails.js but still I have no idea where should I use and write

.create()
,
.find()
etc methods. I know how to define routes in routes.js and how to define controllers. I have created the database connection either.

I know how to use restful and shortcut routes to insert/fetch data from database. But I didn't find anything related to using
.create()
like methods. I found some but they were using Angular.js and Ajax. I didn't understand a thing at all.

Is there any good tutorial where I can learn using models and their methods(how, why and where to write them) without using Angular.js?

Answer

In Sails.js,

Firstly we have to create api, So for example if we need method create for a user. Then we generate api user by typing this command in command prompt

sails generate api user

Then User.js file is generated in api/models folder and UserController.js is generated in api/controllers folder.

Then we have add schema to User.js file

In User.js

module.exports = {
        attributes : {
                lastname : {
                        type : 'string'
                },
                firstname : {
                        type : 'string'
                }
        }
}

We have to write create, find, update and delete methods in UserController.js file. For now will add only create method.

In UserController.js

module.exports = {

      create: function(req, res, next, callback) {
        var params = req.body;

          //create a user
          User.create(params, function(err, createdData) {
              if(err){
                return res.badRequest({
                              error: err
                         });
               } else {
                 return res.json({
                            data : createdData
                 });
               }
          });
        }
    }

Hope this helps.