gpt4 book ai didi

javascript - 如何立即保存在 Sequelize beforeCreate Hook 中?

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:10 28 4
gpt4 key购买 nike

我正在尝试在创建和保存密码之前对其进行哈希处理。但是,当我将 Hook 定义如下时,我注意到日志使用原始密码创建了一个 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

任何和所有的帮助将不胜感激。谢谢!

最佳答案

尝试

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

关于javascript - 如何立即保存在 Sequelize beforeCreate Hook 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040717/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com