Skip to content

Instantly share code, notes, and snippets.

@bluerid
Last active September 6, 2023 08:29
Show Gist options
  • Save bluerid/1b0f411528a441cd86935d0b45bde20f to your computer and use it in GitHub Desktop.
Save bluerid/1b0f411528a441cd86935d0b45bde20f to your computer and use it in GitHub Desktop.
UserSchema.pre("insertMany", async function (next, docs) {
if (Array.isArray(docs) && docs.length) {
const hashedUsers = docs.map(async (user) => {
return await new Promise((resolve, reject) => {
bcrypt.genSalt(10).then((salt) => {
let password = user.password.toString()
bcrypt.hash(password, salt).then(hash => {
user.password = hash
resolve(user)
}).catch(e => {
reject(e)
})
}).catch((e) => {
reject(e)
})
})
})
docs = await Promise.all(hashedUsers)
next()
} else {
return next(new Error("User list should not be empty")) // lookup early return pattern
}
})
UserSchema.pre('save', function (next) {
let user = this
if (!user.isModified("password")) {
next()
} else {
bcrypt.genSalt(10, function (err, salt) {
if (err) return next(err)
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err)
user.password = hash
next()
})
})
}
})
@Asraf2asif
Copy link

Asraf2asif commented Mar 29, 2022

pre-insertMany-middleware.js

// Is this ok? 
const SALT_WORK_FACTOR = 10;
UserSchema.pre('insertMany', async (next, users) => {
  if (Array.isArray(users) && users.length > 0) {
    const hashedUsers = users.map(async (user) => {
      return await new Promise((resolve, reject) => {
        bcrypt
          .genSalt(SALT_WORK_FACTOR)
          .then((salt) => {
            bcrypt
              .hash(user.password.toString(), salt)
              .then((hash) => {
                user.password = hash;
                resolve(user);
              })
              .catch((hashError) => {
                reject(hashError);
              });
          })
          .catch((saltError) => {
            reject(saltError);
          });
      });
    });
    users = await Promise.all(hashedUsers);
    next();
  } else {
    return next(new Error('User list should not be empty')); // lookup early return pattern
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment