Bcrypt Password in Mongodb using Node JS

For Bcrypt the password in MongoDB two things are required first I install the npm package Bcrypt JS and use SALT_WORK_FACTOR. In my user model, I define user Schema where the password field is present and the type is a string.

include require package(bcryptjs) and set SALT_WORK_FACTOR.


var userSchema = new mongoose.Schema({
username: { type: String },
    hash: { type: String } //the password field 
});

For Bcrypt the password in MongoDB two things are required first I install the npm package Bcrypt JS and use SALT_WORK_FACTOR.In my user model, I define user Schema where the password field is present and the type is a string.

  • Password is not hashing until the document or form is saved
  • Mongoose middleware is not invoked on update() operations, So we must use a save() if we want to updated user passwords.

Now use the userSchema.pre() function:


userSchema.pre('save', function(next) {
    var user = this;
    // only hash the password if it has been modified or is new
    if (!user.isModified('hash')) return next();
    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);
        // hashing the password using our new salt
        bcrypt.hash(user.hash, salt, function(err, hash) {  
            if (err) return next(err);
            // override the password with the hashed one
            user.hash = hash;
            next();
        });
    });
});
mongoose.model('user', userSchema);

Conclusion:

This is very important part in NodeJS framework. The above code is developed and tested by me. Please share your review in the comment section. See you on my next blog.

Comment Box

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.