SyntaxStudy
Sign Up
MongoDB Mongoose Middleware and Instance Methods
MongoDB Beginner 1 min read

Mongoose Middleware and Instance Methods

Mongoose middleware (also called hooks) are functions that run before or after certain model operations. Pre-save middleware is commonly used to hash passwords, generate slugs, or validate business rules before a document is written to the database. Post-save middleware can trigger side effects like sending emails or updating caches. Mongoose also lets you define instance methods (available on individual document instances) and static methods (available on the Model class itself). Instance methods access the specific document via this, while static methods are useful for common query patterns you want to encapsulate in the model. Custom validators added to a schema path run automatically during save and can be synchronous or asynchronous.
Example
const bcrypt = require('bcryptjs')

const userSchema = new mongoose.Schema({
  name:     { type: String, required: true },
  email:    { type: String, required: true, unique: true },
  password: { type: String, required: true, minlength: 8 }
}, { timestamps: true })

// PRE-SAVE middleware — hash password before storing
userSchema.pre('save', async function (next) {
  // "this" refers to the document being saved
  if (!this.isModified('password')) return next()
  this.password = await bcrypt.hash(this.password, 12)
  next()
})

// POST-SAVE middleware — side effect after save
userSchema.post('save', function (doc, next) {
  console.log(`User ${doc.email} was saved`)
  next()
})

// INSTANCE METHOD — available on document instances
userSchema.methods.comparePassword = async function (candidatePassword) {
  return bcrypt.compare(candidatePassword, this.password)
}

// STATIC METHOD — available on the Model class
userSchema.statics.findByEmail = function (email) {
  return this.findOne({ email: email.toLowerCase() })
}

const User = mongoose.model('User', userSchema)

// Using instance method
const user = await User.findByEmail('alice@example.com')
const isValid = await user.comparePassword('secret123')

// Using static method
const found = await User.findByEmail('bob@example.com')

This is the last lesson in this section.

Create a free account to earn a certificate