Mongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself.
By using loadClass() method:
- ES6 class methods will become Mongoose methods
- ES6 class statics will become Mongoose statics
- ES6 getters and setters will become Mongoose virtuals
Creating node application And Installing Mongoose:
Step 1: Create a node application using the following command:
mkdir folder_name cd folder_name npm init -y
Step 2: After creating the ReactJS application, Install the required module using the following command:
npm install mongoose
Project Structure: It will look like the following.
Example 1: In this example, we will create a mongoose method using ES6 class
Filename: main.js
const mongoose = require( 'mongoose' )
class MyClass { myMethod() { return "Geeksforgeeks" ; }
} const schema = new mongoose.Schema();
schema.loadClass(MyClass); console.log(schema.methods.myMethod()); |
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Geeksforgeeks
Example 2: In this example, we will create a mongoose static using ES6 class
Filename: main.js
const mongoose = require( 'mongoose' )
class MyClass { static myStatic() { return "Geeksforgeeks" ; }
} const schema = new mongoose.Schema();
schema.loadClass(MyClass); console.log(schema.statics.myStatic()); |
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Geeksforgeeks
Reference: https://mongoosejs.com/docs/guide.html#es6-classes