I'm unable to store bcrypt hashed password from JSON into mongodb using mongoose. I think there is a mistake in my implementation of setPassword schema method. I've replaced 'bcrypt' with 'crypto' implementation and it worked fine. The hashed string was stored in database. But unable to do so with 'bcrypt'
My model.js implementation
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
// User Schema
const userSchema = new Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
}
});
userSchema.methods.setPassword = function(password) {
const saltRounds = 10;
bcrypt.hash(password, saltRounds, function(err, hash) {
this.password = hash;
});
};
mongoose.model('User', userSchema);
My router controller implementation
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');
const register = (req, res) => {
const newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.username = req.body.username;
newUser.setPassword(req.body.password);
newUser.save((err) => {
// Validations error
if (err) {
res.status(400).json(err);
return;
}
res.status(200).json({
success: true,
message: 'Registration Successful'
});
});
};
bcrypt.hashthat you're not verifying.this.password=bcrypt.hashSync(password, saltRounds);