bcryptjs package version:
"bcryptjs": "^2.4.3"
Mongoose library version:
"mongoose": "^6.0.12"
Currently, I am working on encrypting user passwords during user creation or password updates. Everything works smoothly when creating a single user using User.create()
method as the password gets encrypted successfully. However, when I try to use User.insertMany()
to insert multiple users at once, the data is inserted but the passwords are not encrypted. Here is the schema I am using:
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
voterId: {
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 execute this function if password was modified
if (!this.isModified('password')) return next();
// Encrypt the password with salt of 10 rounds
this.password = await bcrypt.hash(this.password, 10);
next();
});
Here is some sample data that I am attempting to insert:
const voters = [
{
name: "Sherali",
surname: "Samandarov",
voterId: "194199",
password: "FA654644", // will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
},
{
name: "Sherali",
surname: "Samandarov",
voterId: "184183",
password: "MB454644", // will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
},
{
name: "Sherali",
surname: "Samandarov",
voterId: "194324",
password: "FA651684", // will be encrypted
isAdmin: false,
finishedVoting: false
// votedFor: [Object], //
}
]
I suspect that the userSchema.pre('save', ...)
logic does not trigger when using insertMany()
method for some unknown reason.