bcryptjs version: "bcryptjs": "^2.4.3"
mongoose version: "mongoose": "^6.0.12"
I am trying to encrypt user password on user creation or password update. Data is inserted successfully but the password is not encrypted. This is my schema (I copied it from my previous project which was working correctly):
import mongoose from 'mongoose'
import bcrypt from 'bcryptjs'
const userSchema = mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
unique: true,
},
votedFor: [
{
type: mongoose.Schema.ObjectId,
ref: 'Election'
}
],
finishedVoting: {
type: Boolean,
required: true,
default: false
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
},
{
timestamps: true,
}
)
userSchema.pre('save', async function(next) {
// Only run this function if password was actually modified
if (!this.isModified('password')) return next();
// Hash the password with salt 10
this.password = await bcrypt.hash(this.password, 10);
next();
});
In the database, I see the password as a plain text(unencrypted). So I tried using callback function instead of async/await
as suggested in other answers:
userSchema.pre('save', function(next) {
var user = this;
console.log("encryption")
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
console.log("started encrypting")
// generate a salt
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
Did not help. I deleted the collection and re-inserted the data. Again the password remains unenrypted. I did not see console.log("encryption")
nor console.log("started encrypting")
while inserting. This is some users data that I am inserting:
const voters = [
{
username: "194199",
password: "FA654644", //will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
},
{
username: "184183",
password: "MB454644", //will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
},
{
username: "194324",
password: "FA651684", //will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
}
]