简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM