Sometimes, we want to hash password with Mongoose.
In this article, we’ll look at how to hash password with Mongoose.
How to hash password with Mongoose?
To hash password with Mongoose, we can use bcrypt
.
For instance, we write
const mongoose = require("mongoose");
const { Schema } = mongoose;
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;
const UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
});
UserSchema.pre("save", function (next) {
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
if (err) return next(err);
bcrypt.hash(this.password, salt, (err, hash) => {
if (err) return next(err);
this.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = (candidatePassword, cb) => {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
module.exports = mongoose.model("User", UserSchema);
to create the User
schema with the password
field.
When we save the User
entry, we call bcrypt.getSalt
to generate the salt.
In the genSalt
callback, we call bcrypt.hash
to hash the password with the salt
created.
And then we set this.password
to hash
and call next
to save.
Then we create the comparePassword
method by setting UserSchema.methods.comparePassword
to a function that calls bcrypt.compare
with the candidatePssword
and this.password
which is current password saved.
We call the cb
callback that we call comparePassword
with in the function and get whether both passwords match with isMatch
.
Then we use it by writing
const testUser = new User({
username: "abc",
password: "password123",
});
testUser.save((err) => {
if (err) throw err;
});
User.findOne({ username: "abc" }, (err, user) => {
if (err) throw err;
user.comparePassword("password123", (err, isMatch) => {
if (err) throw err;
console.log("password123:", isMatch);
});
user.comparePassword("abc", (err, isMatch) => {
if (err) throw err;
console.log("abc:", isMatch);
});
});
to create the testUser
User
.
And then we call findOneto find the user with
usernameset to
‘abc’`.
In the findOne
callback, we call comparePassword
to compare valid and invalid passwords respectively and get whether they match the saved password with isMatch
.
Conclusion
To hash password with Mongoose, we can use bcrypt
.