MongoDB โ Mongoose Middleware & Virtual Properties
Write pre/post save hooks for password hashing and create computed virtual document fields.
1Pre-Save Password Hashing Middleware
Mongoose Pre-Save Hook
import bcrypt from 'bcrypt';
userSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});
// Virtual Property
userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});