水线0.10.14 + express – beforeCreate不执行

我想在我的用户模型上有一个密码,但在创build被调用之前从来没有看到。

使用Express 4.2和水线0.10.14。

用户模式:

var Waterline = require('waterline'), uuid = require('uuid'), bcrypt = require('bcrypt'); var User = module.exports = Waterline.Collection.extend({ identity: 'user', connection: 'default', autoPK: false, // prevents creation of the id schema: true, types: { // Custom Validation - https://github.com/balderdashy/waterline-docs/blob/master/models.md#custom-validations }, attributes: { uuid: { type: 'uuidv4', primaryKey: true, defaultsTo: uuid.v4 }, first_name: { type: 'string', required: true }, last_name: { type: 'string', required: true }, email: { type: 'email', required: true, unique: true }, username: { // TODO: validate no spaces, or special characters type: 'string', required: true, unique: true, index: true, minLength: 3, maxLength: 30 }, password: { // TODO: add rules on password type: 'string', minLength: 6, maxLength: 50, required: true, columnName: 'encrypted_password' }, // TODO: custom input with - https://developers.google.com/places/documentation/autocomplete#place_autocomplete_requests location: { type: 'string' }, activated: { type: 'boolean', defaultsTo: false }, activationToken: { type: 'string' }, // Override toJSON instance method to remove values toJSON: function() { var obj = this.toObject(); // delete obj.password; delete obj.email; delete obj.activated; delete obj.activationToken; return obj; }, verifyPassword: function (password) { return bcrypt.compareSync(password, this.password); }, changePassword: function(newPassword, next){ this.password = newPassword; this.save(function(err, u) { return next(err,u); }); }, // Lifecycle Callbacks beforeCreate: function(attrs, next) { console.log('beforeCreate - user'); bcrypt.genSalt(process.env.SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); bcrypt.hash(attrs.password, salt, function(err, crypted) { if(err) return next(err); attrs.password = crypted; attrs.activationToken = crypto.token(new Date().getTime() + attrs.email); return next(); }); }); }, beforeUpdate: function (attrs, next) { if(attrs.newPassword){ bcrypt.genSalt(process.env.SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); bcrypt.hash(attrs.newPassword, salt, function(err, crypted) { if(err) return next(err); delete attrs.newPassword; attrs.password = crypted; return next(); }); }); } else { return next(); } } } }); 

这是如何被称为我的控制器。

 exports.create = function (req, res, next) { app.models.user.create(req.body, function (err, model) { if(err) return res.error('users/signup', err); res.success('users/welcome', model); }); }; 

我从来没有看到我的beforeCreate调用日志,密码从未散列。 思考?

编辑:用户模型以反映最近的更改。 也应注意beforeCreate应该在validation之前运行。

我想我知道为什么你的beforeCreate没有运行。 这是因为密码是必填字段。 在运行beforeCreatecallback之前,水线实际上运行validationcallback。 由于密码不存在,直到values.password创buildvalidation失败和beforeCreate永远不会被调用。 我假设你只是在创build新用户时传递一个newPassword参数。

这是我的一个小错误,将生命周期callback包装在与我的属性相同的对象中。 他们必须在这个目标之外。