Adding methods to the Mongoose schema is a very useful feature that enables you to encapsulate and reuse business logic at the model level. Here are the steps to add custom methods to a Mongoose schema:
Step 1: Define Schema
First, you need to define a Mongoose Schema. For example, we define a simple User Schema:
javascriptconst mongoose = require('mongoose'); const Schema = mongoose.Schema; let UserSchema = new Schema({ username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true } });
Step 2: Add Instance Methods
Once you have a Schema, you can add instance methods. These methods can be called by any instance of this model.
javascriptUserSchema.methods.encryptPassword = function(password) { // This is the encryption logic, for example, using bcrypt to encrypt the password return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); };
In this example, encryptPassword is an instance method that can be called on any instance of the User model to encrypt the password.
Step 3: Create the Model
After defining the Schema and methods, you need to create the model.
javascriptconst User = mongoose.model('User', UserSchema);
Step 4: Use the Method
Now, you can create a User instance and use the defined methods.
javascriptlet newUser = new User({ username: 'testUser', email: 'test@example.com', password: 'mypassword' }); // Use the instance method newUser.password = newUser.encryptPassword(newUser.password);
This way, you can encrypt the password while creating the user. This is a good example of encapsulating business logic within model methods.
Summary
By adding methods to the Mongoose Schema, you can easily encapsulate business logic at the model level, making the code more modular and reusable. When developing large applications, this approach can improve development efficiency and code quality.