MongoDB โ€” Mongoose Middleware & Virtual Properties

๐Ÿƒ MongoDB 7.0+ ๐ŸŸข Chapter 39 of 50 ๐Ÿ“‚ Phase 08: Application Integration & Multi-Language Drivers ๐Ÿ“… 2026 Edition

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}`;
});
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on MongoDB 7.0+ Standards ยท Last updated August 2026