Writing middleware functions for Mongoose
Middleware functions in Mongoose are also called hooks
. There are two types of hooks pre hooks
and post hooks
.
The difference, between pre hooks
and post hooks, is pretty simple. pre hooks
are called before a method is called, and post hooks
are called after. For example:
const UserSchema = new Schema({ firstName: String, lastName: String, fullName: String, }) UserSchema.pre('save', async function preSave() { this.fullName = `${this.lastName} ${this.firstName}` }) UserSchema.post('save', async function postSave(doc) { console.log(`New user created: ${doc.fullName}`) }) const User = mongoose.model('User', UserSchema)
And later on, once the connection is made to the database, within an async
function:
const user = new User({ firstName: 'John', lastName: 'Smith', }) await user.save()
Once the save
method is called...