Edit Page

Lifecycle callbacks

Overview

#

Lifecycle callbacks are functions that are automagically called before or after certain model actions. For example, we sometimes use lifecycle callbacks to automatically hash a password before creating or updating an Account model.

Sails exposes a handful of lifecycle callbacks by default.

Callbacks on create
#
Callbacks on update
#
Callbacks on destroy
#

Example

#

If you want to hash a password before saving in the database, you might use the beforeCreate lifecycle callback.

var bcrypt = require('bcrypt');

module.exports = {

  attributes: {

    username: {
      type: 'string',
      required: true
    },

    password: {
      type: 'string',
      minLength: 6,
      required: true,
      columnName: 'hashed_password'
    }

  },


  // Lifecycle Callbacks
  beforeCreate: function (values, cb) {

    // Hash password
    bcrypt.hash(values.password, 10, function(err, hash) {
      if(err) return cb(err);
      values.password = hash;
      //calling cb() with an argument returns an error. Useful for canceling the entire operation if some criteria fails.
      cb();
    });
  }
};

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.