Last active
September 6, 2023 08:29
-
-
Save bluerid/1b0f411528a441cd86935d0b45bde20f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
}) | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pre-insertMany-middleware.js