Edit Page

.create()

Create a record in the database.

Something.create(values).exec(function (err, record) {

});

Usage

Argument Type Details
1 values The attributes that the new record should have.
Callback
Argument Type Details
1 err The error that occurred, or null if there were no errors. See below for an example of how to negotiate validation errors (e.g. attempting to insert a record that would violate a uniqueness constraint)
2 newRecord The newly-created record, with its primary key (usually id) set.

Example

To create a user named Finn in the database:

User.create({name:'Finn'}).exec(function (err, finn){
  if (err) { return res.serverError(err); }

  sails.log('Finn\'s id is:', finn.id);
  return res.ok();
});
Negotiating Validation Errors

Originally posted in #3459

var Passwords = require('machinepack-passwords');


module.exports = {

  signup: function (req, res) {
    // Encrypt a string using the BCrypt algorithm.
    Passwords.encryptPassword({
      password: req.param('password'),
    }).exec({
      // An unexpected error occurred encrypting the password.
      error: function (err){
        return res.serverError(err);
      },
      // OK.
      success: function (encryptedPassword) {

        // Create a user record in the database.
        User.create({
          email: req.param('email'),
          password: encryptedPassword
        }).exec(function (err, newUser) {
          // If there was an error, we negotiate it.
          if (err) {

            // If this is NOT a waterline validation error, it is a mysterious error indeed.
            var isWLValidationErr = _.isObject(err) && _.isObject(err.invalidAttributes);
            if (!isWLValidationErr) {
              return res.serverError(err);
            }

            // Otherwise, it must be a waterline validation error.

            // If it doesn't contain a problem with the password, then just handle is
            // using `res.badRequest()` like normal.
            if (!_.isArray(err.invalidAttributes.password)) {
              return res.badRequest(err);
            }

            // Otherwise, something was wrong with the provided encrypted password.
            // So in this case, we'll modify the validation error in place to improve the error output
            // and so that we don't inadvertently reveal info about the encrypted password.
            // (specifically, we loop over the array of attribute errors and modify them).
            err.invalidAttributes.password = _.map(err.invalidAttributes.password, function eachPasswordErr (passwordError) {
              return _.reduce(passwordError, function (memo, val, key) {
                var allOccurrencesOfEncryptedPassMatcher = new RegExp(_.escapeRegExp(encryptedPassword),'g');
                memo[key] = val.replace(allOccurrencesOfEncryptedPassMatcher, '****');
                return memo;
              }, {});
            });

            // Finally, respond with the modified waterline validation error and a 400 status code.
            return res.badRequest(err);

          }//</if (err)>

          // Otherwise, `err` was falsy, so it worked!  The user was created.
          // (maybe do other stuff here, or just send a 200 OK response)
          return res.ok();

        });//</User.create>
      }
    });//</Passwords.encryptPassword>
  }//</UserController.signup>
};

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails-docs repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Sails logo
  • Home
  • Get started
  • Support
  • Documentation
  • Documentation

For a better experience on sailsjs.com, update your browser.

Documentation

Reference Concepts App structure | Upgrading Contribution guide | Tutorials More

Reference

  • Application
    • Events
    • Lifecycle
    • sails.getRouteFor()
    • sails.getUrlFor()
    • sails.lift()
    • sails.load()
    • sails.log()
    • sails.lower()
    • sails.request()
    • sails.getBaseUrl()
  • Blueprint API
    • add to
    • create
    • destroy
    • find one
    • find where
    • populate where
    • remove from
    • update
  • Command Line Interface
    • sails console
    • sails debug
    • sails generate
    • sails lift
    • sails new
    • sails version
  • Configuration
    • sails.config.*
    • sails.config.blueprints
    • sails.config.bootstrap()
    • sails.config.connections
    • sails.config.cors
    • sails.config.csrf
    • sails.config.globals
    • sails.config.http
    • sails.config.i18n
    • sails.config.log
    • sails.config.models
    • sails.config.policies
    • sails.config.routes
    • sails.config.session
    • sails.config.sockets
    • sails.config.views
  • Request (`req`)
    • req.accepted
    • req.acceptedCharsets
    • req.acceptedLanguages
    • req.body
    • req.cookies
    • req.fresh
    • req.headers
    • req.host
    • req.ip
    • req.ips
    • req.isSocket
    • req.method
    • req.options
      • req.options.values
      • req.options.where
    • req.originalUrl
    • req.params
    • req.path
    • req.protocol
    • req.query
    • req.secure
    • req.signedCookies
    • req.socket
    • req.subdomains
    • req.url
    • req.wantsJSON
    • req.xhr
    • req.accepts()
    • req.acceptsCharset()
    • req.acceptsLanguage()
    • req.allParams()
    • req.file()
    • req.get()
    • req.is()
    • req.param()
  • Response (`res`)
    • res.attachment()
    • res.badRequest()
    • res.clearCookie()
    • res.cookie()
    • res.created()
    • res.forbidden()
    • res.get()
    • res.json()
    • res.jsonp()
    • res.location()
    • res.negotiate()
    • res.notFound()
    • res.ok()
    • res.redirect()
    • res.send()
    • res.serverError()
    • res.set()
    • res.status()
    • res.type()
    • res.view()
  • Waterline (ORM)
    • Models
      • .count()
      • .create()
      • .destroy()
      • .find()
      • .findOne()
      • .findOrCreate()
      • .native()
      • .query()
      • .stream()
      • .update()
    • Populated Values
      • .add()
      • .remove()
    • Queries
      • .exec()
      • .limit()
      • .populate()
      • .skip()
      • .sort()
      • .where()
    • Records
      • .save()
      • .toJSON()
      • .toObject()
  • WebSockets
    • Resourceful PubSub
      • .message()
      • .publishAdd()
      • .publishCreate()
      • .publishDestroy()
      • .publishRemove()
      • .publishUpdate()
      • .subscribe()
      • .unsubscribe()
      • .unwatch()
      • .watch()
      • .subscribers()
    • sails.sockets
      • .addRoomMembersToRooms()
      • .blast()
      • .broadcast()
      • .getId()
      • .join()
      • .leave()
      • .leaveAll()
      • .removeRoomMembersFromRooms()
      • sails.sockets.emit()
      • sails.sockets.id()
      • sails.sockets.rooms()
      • sails.sockets.socketRooms()
      • sails.sockets.subscribers()
    • Socket Client
      • io.sails
      • io.socket
      • SailsSocket
        • Methods
        • Properties
      • io.socket.delete()
      • io.socket.get()
      • io.socket.off()
      • io.socket.on()
      • io.socket.post()
      • io.socket.put()
      • io.socket.request()

Built with Love

The Sails framework is maintained by a web & mobile studio in Austin, TX, with the help of our contributors. We created Sails in 2012 to assist us on Node.js projects. Naturally we open-sourced it. We hope it makes your life a little bit easier!

Sails:
  • What is Sails?
  • Treeline IDE
  • Contribute
  • Logos/artwork
About:
  • The Sails Company
  • Security
  • News
  • Legal
Help:
  • Get started
  • Documentation
  • Docs
  • Enterprise
  • Hire us

© 2012-2018 The Sails Company. 
The Sails framework is free and open-source under the MIT License.