Reputation: 6269
I have a user
schema that when i add a new one to the database it hashes the password
in the pre(save)
hook but i want to do the same while updating but it saves the plain password instead of hashed one
this works fine while creating new record
UserSchema.pre('save', async function (done) {
if (this.isModified('password')) {
const hashedPassword = await Password.hash(this.get('password'));
this.set('password', hashedPassword);
}
done(null);
});
but this didn't work fine
UserSchema.pre('updateOne', async function (done) {
const hashedPassword = await Password.hash(this.get('password'));
this.set('password', hashedPassword);
done(null);
});
NOTE: there are no errors in the console
Upvotes: 0
Views: 266
Reputation: 655
mongoosejs.com/docs/middleware.html#pre
if you define pre('updateOne') document middleware, this will be the document being updated. That's because pre('updateOne') document middleware hooks into Document#updateOne() rather than Query#updateOne(), so it should be
schema.pre('updateOne', { document: true, query: false }, function() { console.log('Updating'); })
Upvotes: 2