[英]bcrypt hash all password in array
I have an array of objects with "users" that each have a username, name and password property.我有一组带有“用户”的对象,每个对象都有一个用户名、名称和密码属性。 I want to hash each user's password, create a User object with same properties but omit the password for a hash, and then return it using map() before saving and then finish it off with Promise.all()
I want to hash each user's password, create a User object with same properties but omit the password for a hash, and then return it using map() before saving and then finish it off with Promise.all()
const initialUsersArray = [
{
username: 'user1',
name: 'User McUser',
password: 'abcd'
},
{
username: 'user2',
name: 'User Usersson',
password: '1234'
},
const SALT_WORK_FACTOR = 10;
const hashedUsers= initialUsersArray.map(async (user) => {
const hashedPassword = await bcrypt.hash(user.password, SALT_WORK_FACTOR);
return new User({
username: user.username,
name: user.name,
hashedPassword
});
});
const promiseArray = hashedUsers.map(user => user.save());
await Promise.all(promiseArray);
The issue is that it doesn't wait for the promises to resolve before trying to save() each user.问题是在尝试 save() 每个用户之前它不会等待承诺解决。 If I console.log hashedUsers I get an array of
Promise { <pending> },
如果我 console.log hashedUsers 我得到一个
Promise { <pending> },
I'm missing something on how Promises works inside map(), above works just fine if I just use it for a single user, like this我遗漏了一些关于 Promises 在 map() 中如何工作的内容,如果我只将它用于单个用户,上面的工作就很好,就像这样
const hashedPassword = await bcrypt.hash(password, SALT_WORK_FACTOR);
const user = new User({
username: username,
name: name,
hashedPassword,
});
await user.save()
You could try the code below it is working as expected, I just tested it!您可以尝试下面的代码,它按预期工作,我刚刚测试过!
The problem with your code is that you're not waiting for hashedUsers
to resolve, hashedUsers
has pending promises which you should await
, you could first do await Promise.all(hashedUsers)
and then await .save()
, but you could do this in once shot as mentioned in the code below.你的代码的问题是你没有等待
hashedUsers
解决, hashedUsers
有你应该await
的未决承诺,你可以先做await Promise.all(hashedUsers)
然后 await .save()
,但你可以这样做一次拍摄,如下面的代码中所述。
const userSchema = new mongoose.Schema({
user: String,
name: String,
hashedPassword: String,
});
const User = mongoose.model("User", userSchema);
const initialUsersArray = [
{
username: "user1",
name: "User McUser",
password: "abcd",
},
{
username: "user2",
name: "User Usersson",
password: "1234",
},
];
const SALT_WORK_FACTOR = 10;
const hashedUsers = initialUsersArray.map(async (user) => {
const hashedPassword = await bcrypt.hash(user.password, SALT_WORK_FACTOR);
const userDoc = await new User({
username: user.username,
name: user.name,
hashedPassword,
}).save();
return userDoc;
});
const main = async () => {
const promiseArray = await Promise.all(hashedUsers);
console.log(promiseArray);
};
main();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.