ShaSha
ShaSha

Reputation: 699

How to hash password before saving user in node js and mongoose

this is my user model:

const schema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    min: 6,
    max: 255
  },
  email: {
    type: String,
    required: true,
    min: 6,
    max: 255
  },
  password: {
    type: String,
    required: true,
    max: 1024,
    min: 6
  }
});

schema.pre("save", async next => {
  if (!this.isModified("password")) return next();
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    return next();
  } catch (error) {
    return next(erro);
  }
});

module.exports = mongoose.model("User", schema);

when i save user, it return empty object and it doesn't save and not working. i don't know what should to do? what is the problem?

Upvotes: 2

Views: 2885

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17888

You should use function form instead of arrow function inside the pre save middleware. Because Arrow functions do not bind their own this.

schema.pre("save", async function(next) {
  if (!this.isModified("password")) return next();
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    return next();
  } catch (error) {
    return next(error);
  }
});

Upvotes: 3

Related Questions