MongoDB
Beginner
1 min read
Mongoose Middleware and Instance Methods
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')
Related Resources
This is the last lesson in this section.
Create a free account to earn a certificate