How to prevent Mongoose from rehashing the user passwords after modifying a user?
mongoose, schema
Solution
Maybe you can check whether the password was modified or not - using isModified.
userSchema.pre('save', function(next) {
const user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
Problem
Many tutorials out there, tell to use bycrypt within your userSchema page. Once you save a new user, it goes with the encrypted passwords. Great. Yet, I figured, that when I edit the user with something, it also rehashes the password, making impossible to log in. Could you please suggest me a solution? Thank you. ``` const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bcrypt-nodejs'); const eventSchema = require('./eventSchema'); const userSchema = new Schema({ email: { type: String, unique: true, lowercase: true }, password: String, eventList: [{ type: Schema.ObjectId, ref: "event" }], administrator: { type: Boolean, default: false } }); // On Save Hook, encrypt password // Before saving a model, run this function userSchema.pre('save', function(next) { // get access to the user model const user = this; // generate a salt then run callback bcrypt.genSalt(10, function(err, salt) { if (err) { return next(err); } // hash (encrypt) our password using the salt bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) { return next(err); } // overwrite plain text password with encrypted password user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return callback(err); } callback(null, isMatch); }); }; // Create the model class const ModelClass = mongoose.model('user', userSchema); // Export the model module.exports = ModelClass; ```