簡體   English   中英

bcrypt hash 數組中的所有密碼

[英]bcrypt hash all password in array

我有一組帶有“用戶”的對象,每個對象都有一個用戶名、名稱和密碼屬性。 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);

問題是在嘗試 save() 每個用戶之前它不會等待承諾解決。 如果我 console.log hashedUsers 我得到一個Promise { <pending> },

我遺漏了一些關於 Promises 在 map() 中如何工作的內容,如果我只將它用於單個用戶,上面的工作就很好,就像這樣

const hashedPassword = await bcrypt.hash(password, SALT_WORK_FACTOR);
const user = new User({
  username: username,
  name: name,
  hashedPassword,
});
await user.save()

您可以嘗試下面的代碼,它按預期工作,我剛剛測試過!

你的代碼的問題是你沒有等待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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM