Document middleware functions

Create pre and post hooks for the document built-in methods:

  1. Create a new file named 1-document-middleware.js
  2. Include the Mongoose NPM module and create a new connection to your MongoDB:
      const mongoose = require('mongoose') 
      const { connection, Schema } = mongoose 
      mongoose.connect( 
          'mongodb://localhost:27017/test' 
      ).catch(console.error) 
  1. Define a schema:
      const UserSchema = new Schema({ 
          firstName: { type: String, required: true }, 
          lastName: { type: String, required: true }, 
      }) 
  1. Add a pre and post hook for the init document method:
      UserSchema.pre('init', async function preInit() { 
          console.log('A document is going to be initialized.') 
      }) 
      UserSchema.post('init', async function postInit() { 
          console.log('A document was initialized.') 
      }) 
  1. Add a pre and post hook for the validate document method:
      UserSchema.pre('validate', async function preValidate() { 
          console.log('A document is going to be validated.') 
      }) 
      UserSchema.post('validate', async function postValidate() { 
          console.log('All validation rules were executed.') 
      }) 
  1. Add a pre and post hook for the save document method:
      UserSchema.pre('save', async function preSave() { 
          console.log('Preparing to save the document') 
      }) 
      UserSchema.post('save', async function postSave() { 
          console.log(`A doc was saved id=${this.id}`) 
      }) 
  1. Add a pre and post hook for the remove document method:
      UserSchema.pre('remove', async function preRemove() { 
          console.log(`Doc with id=${this.id} will be removed`) 
      }) 
      UserSchema.post('remove', async function postRemove() { 
          console.log(`Doc with id=${this.id} was removed`) 
      }) 
  1. Compile the schema into a model:
      const User = mongoose.model('User', UserSchema) 
  1. Once a new connection is established, create a document and perform some basic operations such as saving, retrieving, and deleting the document:
      connection.once('connected', async () => { 
          try { 
              const user = new User({ 
                  firstName: 'John', 
                  lastName: 'Smith', 
              }) 
              await user.save() 
              await User.findById(user.id) 
              await user.remove() 
              await connection.close() 
          } catch (error) { 
              await connection.close() 
              console.dir(error.message, { colors: true }) 
          } 
      }) 
  1. Save the file
  2. Open a Terminal and run:
      node document-middleware.js
  1. On the terminal, the output should display:
      A document is going to be validated. 
      All validation rules were executed. 
      Preparing to save the document 
      A doc was saved id=[ID] 
      A document is going to be initialized. 
      A document was initialized. 
      Doc with id=[ID] will be removed 
      Doc with id=[ID] was removed 

When you save a document, it first triggers the validation hooks that ensure that the fields pass the rules set by built-in validation rules or custom rules. In your code, the fields are marked as required. Then it will trigger the save hooks. After, using a model method to retrieve the recently created user from the database, once the document is retrieved, it triggers the init hooks. Finally, removing the document from the database triggers the remove hooks.

Within the hooks, you can interact with the document. For instance, the following save pre hook will modify the fields firstName and lastName to make them upper-cased strings:

UserSchema.pre('save', async function preSave() { 
    this.firstName = this.firstName.toUpperCase() 
    this.lastName = this.lastName.toUpperCase() 
}) 

The same way, we can throw an error within the hook to prevent the next ones from being executed. For instance:

UserSchema.pre('save', async function preSave() { 
    throw new Error('Doc was prevented from being saved.') 
}) 

Query middleware functions are defined exactly as document middleware functions are. However, the context of this doesn't not refer to the document but instead to the query object. Query middleware functions are only supported in the following model and query functions:

  • count: Counts the number of document that match a specific query condition
  • find: Returns an array of documents that match a specific query condition
  • findOne: Return a document that matches a specific query condition
  • findOneAndRemove: Similar to findOne. However, after a document is found, it is removed
  • findOneAndUpdate: Similar to findOne but once a document matching a specific query condition is found, the document can also be updated
  • update: Update one or more documents that match a certain query condition
..................Content has been hidden....................

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