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:
- schema: Schema parameter lets you add to the particular schema. It is required.
- options: Options parameter lets you define tunable parameters for your plugin. It is an optional parameter.
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.
- Creating a custom plugins function
- Installing an npm mongoose plugins package
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
module.exports = exports =
function time_plugins(schema, options) {
// Adding created at and last access
// date and time to the schema
schema.add({ lastAccess: Date });
schema.add({ createdAt: Date });
// This will executed when save
// function is called
schema.pre('save', function (next) {
this.createdAt = new Date()
this.lastAccess = new Date();
next()
});
// It will execute when find function
// is called and update last access
// value to current date and time
schema.post('find', async function (result) {
if (result) {
await this.updateMany({}, {
lastAccess: new Date()
}, ).clone();
}
});
}
Step 3. Then create app.js and add the below code.
JavaScript
const mongoose = require('mongoose');
const url = 'mongodb://127.0.0.1:27017/test';
const conn = mongoose.connect(url);
mongoose.set('strictQuery', false)
// User Schema
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: type: String
});
userSchema.plugin(require('./plugs'));
// Compile the schema into a model
const User = mongoose.model('User', userSchema);
// Save a new user to the database
const user = new User({
name: 'Geeks for Geeks',
email: '[email protected]',
password: 'mongoose'
});
user.save();
// find functions
User.find();
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
const mongoose = require('mongoose');
const url = 'mongodb://127.0.0.1:27017/test';
const conn = mongoose.connect(url);
// This will add the plugin to all the schemas
mongoose.plugin("./plugs")
mongoose.set('strictQuery', false)
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
const booksSchema = new mongoose.Schema({
name: String,
author: String,
})
// Compile the schema into a model
const User = mongoose.model('User', userSchema);
const Book = mongoose.model('Book', bookSchema);
// Save a new user to the database
const user = new User({
name: 'Geeks for Geeks',
email: '[email protected]',
password: 'mongoose'
});
const book = new Book({
name: "Mongoose Guides",
author: "Geeks"
});
user.save();
books.save();
User.find({}, function (err, docs) { });
Book.find({}, function (err, docs) { });
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
const mongoose = require('mongoose');
// Mongodb Connection URL
const url = 'mongodb://127.0.0.1:27017/test';
const conn = mongoose.connect(url, {}) //
console.log("MongoDB is Connected")
// Creates a Schema
const userSchema = new mongoose.Schema({
name: String,
email: String,
// Specify the property to be hidden
password: {
type: String,
hide: true
}
});
// Add a plugin to the schema
userSchema.plugin(require('mongoose-hidden')());
// Compile the schema into a model
const User = mongoose.model('User', userSchema);
// Save a new user to the database
const user = new User({
name: 'Geeks for Geeks',
email: '[email protected]',
password: 'mongoose'
});
user.save();
// Print the data
console.log(user.toJSON())
Step 3: Run the code using the following command
node app.js
Output:
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read