如何在Sequelize beforeCreate钩子中立即保存?

时间:2016-06-26 16:35:09

标签: javascript node.js sequelize.js

我尝试在创建和保存之前对密码进行哈希处理。但是,当我将hooked定义如下时,我注意到日志创建了一个带有原始密码的guest实例,然后立即更新它。我不确定为什么。

// define model

const Guest = sequelize.define('guest', {
  email: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  }
});

Guest.beforeCreate(function(guest) {
  bcrypt.genSalt(10, function(error, salt) {
    if (error) { return error }
    bcrypt.hash(guest.password, salt, null, function(error, hash) {
      if (error) { return error }
      guest.password = hash;
      guest.save();
    })
  })
});

这是我实际在另一个文件中创建实例的地方

//..

const email = req.body.email;
const password = req.body.password;

Guest.findOne({ where: { email: email }})
  .then(function(existingUser) {

    if (existingUser) {
      return res.status(422).send({ error: 'Email is already in use'})
    }

    Guest.create({
      email: email,
      password: password
    }).then(function(guest) {
      res.json({ token: tokenForGuest(guest) });
    });

  });

但是,当我这样做时,它会立即使用此密码创建实例(不是使用提供的密码创建,然后使用我设置的更新):

Guest.beforeCreate(function(guest) {
     guest.password = 'TEST';
    });

这是我的服务器日志:

Executing (default): SELECT "id", "email", "password", "createdAt", "updatedAt"
FROM "guests" AS "guest" WHERE "guest"."email" = 'mytestemail@example.com' LIMIT
 1;

Executing (default): INSERT INTO "guests" 
("id","email","password","createdAt","updatedAt") VALUES 
(DEFAULT,'mytestemail@example.com','passwordsecret123','2016-06-26 16:26:54.683 
+00:00','2016-06-26 16:26:54.683 +00:00') RETURNING *;
::1 - - [26/Jun/2016:16:26:55 +0000] "POST /signup HTTP/1.1" 200 133 "-" 
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like 
Gecko) Postman/4.2.2 Chrome/47.0.2526.73 Electron/0.36.2 Safari/537.36"

Executing (default): UPDATE "guests" SET 
"password"='$2a$10$VsU97hLMxZ76zGmNfJVlfOeXayyFbGMKK/EwE3SvKhOOEi9oAm9Qy',"updated
At"='2016-06-26 16:26:55.428 +00:00' WHERE "id" = 20

非常感谢任何和所有帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

Guest.beforeCreate(function(guest, options, done) {
    bcrypt.genSalt(10, function(err, salt) {
        if (err) return done(err);
        console.log('Salt: ' + 'getting ' + salt);
        bcrypt.hash(guest.password, salt, null, function(err, hash) {
            if (err) return done(err);

            console.log('Info: ' + 'getting ' + hash);

            guest.password = hash;

            console.log('Info: ' + 'password now is: ' + guest.password);

            return done(null,guest);
        });
    });
});