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, the pre hook is executed first. After the document is saved, the post hook is then executed. In the previous example, it will display in the Terminal output the following text:

    New user created: Smith John

There are four different types of middleware functions in Mongoose: document middleware, model middleware, aggregate middleware, and query middleware. All of them are defined on the schema level. The difference is, when the hooks are executed, the context ofthis refers to the document, model, the aggregation object, or the query object.

All types of middleware support pre and post hooks
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.7