使用beforeCreate钩子创build模型

我之前定义了我的钩子创build如下:

module.exports = function (sequelize, DataTypes) { var userSchema = sequelize.define('User', { // define... }); userSchema.beforeCreate(function (model) { debug('Info: ' + 'Storing the password'); model.generateHash(model.password, function (err, encrypted) { debug('Info: ' + 'getting ' + encrypted); model.password = encrypted; debug('Info: ' + 'password now is: ' + model.password); // done; }); }); }; 

当我创build一个模型

  User.create({ name: req.body.name.trim(), email: req.body.email.toLowerCase(), password: req.body.password, verifyToken: verifyToken, verified: verified }).then(function (user) { debug('Info: ' + 'after, the password is ' + user.password); }).catch(function (err) { // catch something }); 

现在我从中得到了什么

 Info: Storing the password +6ms Info: hashing password 123123 +0ms // debug info calling generateHash() Executing (default): INSERT INTO "Users" ("id","email","password","name","verified","verifyToken","updatedAt","createdAt") VALUES (DEFAULT,'wwx@test.com','123123','wwx',true,NULL,'2015-07-15 09:55:59.537 +00:00','2015-07-15 09:55:59.537 +00:00') RETURNING *; Info: getting $2a$10$6jJMvvevCvRDp5E7wK9MNuSRKjFpieGnO2WrETMFBKXm9p4Tz6VC. +0ms Info: password now is: $2a$10$6jJMvvevCvRDp5E7wK9MNuSRKjFpieGnO2WrETMFBKXm9p4Tz6VC. +0ms Info: after, the password is 123123 +3ms 

看来代码的每个部分都在起作用。 创build一个用户模式将调用beforeCreate,它正确地生成密码的哈希码….除了它没有写入数据库!

我确定我错过了一个非常重要和明显的代码段,但是我找不到问题所在(唉)。 任何帮助感激!

挂钩在Sequelize中以asynchronous方式被调用,所以当你完成时你需要调用完成callback:

 userSchema.beforeCreate(function(model, options, cb) { debug('Info: ' + 'Storing the password'); model.generateHash(model.password, function(err, encrypted) { if (err) return cb(err); debug('Info: ' + 'getting ' + encrypted); model.password = encrypted; debug('Info: ' + 'password now is: ' + model.password); return cb(null, options); }); }); 

(或者,你可以从挂钩返回一个承诺)

对于较新版本的Sequelize来说,钩子不再有callback函数,而是保证。 因此,代码看起来更像以下内容:

 userSchema.beforeCreate(function(model, options) { debug('Info: ' + 'Storing the password'); return new Promise ((resolve, reject) => { model.generateHash(model.password, function(err, encrypted) { if (err) return reject(err); debug('Info: ' + 'getting ' + encrypted); model.password = encrypted; debug('Info: ' + 'password now is: ' + model.password); return resolve(model, options); }); }); });