简体   繁体   中英

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()

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. If I console.log hashedUsers I get an array of 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM