0

After testing model creation, I noticed that lifecycle callbacks were not getting called and upon reading Waterline's documentation I found:

NOTE: When using custom adapter methods the features of Waterline are not used. You no longer get the Lifecycle Callbacks and Validations as you would when using a defined Waterline method.

Though, I haven't knowingly used a custom adapter method, and that is the only reference I could find in the documentation about lifecycle callbacks getting disabled.

What criteria/setting of whichever files in config/* should I have to absolutely ensure that lifecycle callbacks are not disabled?

Here is a copy of my model for which the only lifecycle callback I use does not get called:

/**
* User.js
*
*/

var bcrypt = require('bcrypt');

module.exports = {
attributes: {
'email': {
        type: 'email',
        required: true,
        unique: true
},

'username': {
        type: 'string',
        required: true,
        unique: true,
        minLength: 5,
        maxLength: 16
},

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

'family': {
        model: 'family'
},

'lastlogin': {
        type: 'datetime',
        defaultsTo: function() {return new Date().toISOString();}
},

    beforeCreate: function(obj, cb) {
        console.log("In beforeCreate");
        bcrypt.hash(obj.password, 10, function(err, hash) {
            if (err) {
                console.log(err);
                return cb(err);
            }

            obj.password = hash;
            cb();
        });
    }
  }
};`
  • That note should have no bearing unless you are using a custom method. Are you using a custom method? You may want to post an example of your code. – Meeker Feb 17 '15 at 23:02
  • Not that I know of, but I added it because it was the only reference in the Waterline documentation I can find about disabled lifecycle callbacks. – Francesco Gramano Feb 17 '15 at 23:06

1 Answers1

2

Your callback need to be on the exports object, its not an attribute.

/**
* User.js
*
*/

var bcrypt = require('bcrypt');

module.exports = {
attributes: {
'email': {
        type: 'email',
        required: true,
        unique: true
    },

'username': {
        type: 'string',
        required: true,
        unique: true,
        minLength: 5,
        maxLength: 16
    },

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

'family': {
        model: 'family'
    },

'lastlogin': {
        type: 'datetime',
        defaultsTo: function() {return new Date().toISOString();}
    },

},

beforeCreate: function(obj, cb) {
    console.log("In beforeCreate");
    bcrypt.hash(obj.password, 10, function(err, hash) {
        if (err) {
            console.log(err);
            return cb(err);
        }

        obj.password = hash;
        cb();
    });
   }

};
Meeker
  • 5,979
  • 2
  • 20
  • 38