I am using bcryptjs to hash passwords before storing inside mongodb but it store passwords as plaintext(no hashing).this is my userModel.js
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const userSchema = new mongoose.Schema(
{
mobile: {
type: String,
},
password: {
type: String,
},
},
{ timestamps: true }
);
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
userSchema.pre("save", async function (next) {
console.log("pre save called");
if (!this.isModified("password")) {
next();
}
const salt = await bcrypt.genSalt(10);
this.password = bcrypt.hash(this.password, salt);
});
const User = mongoose.model("User", userSchema);
module.exports = User;
my register controller is written like this
module.exports.register = asynchandler(async (req, res) => {
const { mobile, password } = req.body;
const user = await User.findOne({ mobile });
if (user) {
res.status(400).json({ message: "user already exists" });
} else {
const newUser = await User.create({
mobile,
password,
});
res.status(200).json(newUser);
}
});
but when I test API using postman password saved as a plaintext(no hashing)
2
Answers
I finally found the solution. I don't know why but using below code worked properly.
you should not use create method , u need to use save () method