本文介绍了使用 beforeCreate 钩子续写创建模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的钩子定义为 beforeCreate 如下:

I defined my hook beforeCreate as following:

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;
    });
  });
};

当我创建模型时

  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,'[email protected]','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

似乎代码的每一部分都在工作.创建用户架构将调用 beforeCreate,它会正确生成密码的哈希码......除非它没有写入数据库!

It seems that every part of the code is working. Creating a user schema will invoke beforeCreate, which properly generates the hash code for the password.... except it didn't write to the database!

我确定我遗漏了一段非常重要且明显的代码,但我就是找不到问题出在哪里(啊哈).任何帮助表示赞赏!

I'm certain that I'm missing a very important and OBVIOUS piece of code, but I just can't find where the problem is (aghh). Any help appreciated!

推荐答案

Hooks 在 Sequelize 中以异步方式调用,因此您需要在完成后调用完成回调:

Hooks are called in an asynchronous fashion in Sequelize, so you need to call the completion callback when you're done:

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);
  });
});

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

(alternatively, you can return a promise from the hook)

这篇关于使用 beforeCreate 钩子续写创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 12:43