![]() |
Plugins are a technique for reusing logic in multiple mongoose schemas. A plugin is similar to a method that you can use in your schema and reuse repeatedly over different instances of the schema. The main purpose of plugins is to modify your schemas. Plugins don’t have anything to do with models or documents, so they can’t execute queries or write to the database directly. A mongoose plugin is a JavaScript method that takes two parameters: the Schema, and an optional Options object. Syntax: function plugin_name(schema, options) {} Parameters:
Installation of mongoose module: Step 1: Create a folder and inside the terminal enter the following command to install node_modules. npm init -y Step 2: Install mongoose using the following command. npm i mongoose Step 3: After installing you can check the version using the following command. npm info mongoose version Step 4: After that create an index.js file and run it using the following command. node index.js We can add plugins in two ways to our schema.
Example 1: We want to create a plugin that can automatically save the creation timestamp Step 1: Open a folder initialize the node project and install mongoose npm init -y npm i mongoose Step 2: Then create the plugs.js file and add the below code:
Javascript
Step 3. Then create app.js and add the below code.
Javascript
Step 4. Run the code by writing the below command node app.js You can use any GUI tool or terminal to see the database like we have used the MongoDB compass GUI tool as shown below: Output: ![]()
Example 2: In this example, we will use the mongoose.plugin() to add the plugins to all the schema in the database Step 1: Just add the plugin in the mongoose.plugin() and it will be added to all the plugins as shown below.
Javascript
Step 2: Run the code using the following command node app.js Output: ![]()
![]()
As you can see both schemas has the same plugin functionality. Example 3: In this example, we have the same database but instead we will use a mongoose plugin module mongoose-hidden Mongoose-hidden plugin is used to hide properties you do not want to send to the client example password, keys, etc. It works with toJSON() and toObjects() Step 1: Install the mongoose-hidden module using the below command. npm i mongoose-hidden Step 2: Add the mongoose-hidden plugin to the schema and specify the hidden property to true in the schema definition.
Javascript
Step 3: Run the code using the following command node app.js Output: ![]()
|
Reffered: https://www.geeksforgeeks.org
Node.js |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |