0

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)
Aliking66
  • 31
  • 7

2 Answers2

0

I finally found the solution. I don't know why but using below code worked properly.

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }
  bcrypt.hash(this.password, 10, (err, hash) => {
    if (err) {
      console.log("something went wrong for hashing");
    }
    if (hash) {
      this.password = hash;
    }
  });
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Aliking66
  • 31
  • 7
0

you should not use create method , u need to use save () method

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 = new User({
        mobile,
        password,
    });
    await newUser.save()
    res.status(200).json(newUser);
  }
});
Venkatesh
  • 58
  • 8