Mongoose Plugins
Last Updated :
31 Mar, 2023
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) {
schema.add({ lastAccess: Date });
schema.add({ createdAt: Date });
schema.pre( 'save' , function (next) {
this .createdAt = new Date()
this .lastAccess = new Date();
next()
});
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 conn = mongoose.connect(url);
mongoose.set( 'strictQuery' , false )
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: type: String
});
userSchema.plugin(require( './plugs' ));
const User = mongoose.model( 'User' , userSchema);
const user = new User({
name: 'Geeks for Geeks' ,
email: 'geeksforgeeks@gfg.com' ,
password: 'mongoose'
});
user.save();
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 conn = mongoose.connect(url);
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,
})
const User = mongoose.model( 'User' , userSchema);
const Book = mongoose.model( 'Book' , bookSchema);
const user = new User({
name: 'Geeks for Geeks' ,
email: 'geeksforgeeks@gfg.com' ,
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' );
const conn = mongoose.connect(url, {})
console.log( "MongoDB is Connected" )
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: {
type: String,
hide: true
}
});
userSchema.plugin(require( 'mongoose-hidden' )());
const User = mongoose.model( 'User' , userSchema);
const user = new User({
name: 'Geeks for Geeks' ,
email: 'geeksforgeeks@gfg.com' ,
password: 'mongoose'
});
user.save();
console.log(user.toJSON())
|
Step 3: Run the code using the following command
node app.js
Output:
Share your thoughts in the comments
Please Login to comment...