乐闻世界logo
搜索文章和话题

How to add schema method in mongoose?

1个答案

1

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:

javascript
const 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.

javascript
UserSchema.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.

javascript
const User = mongoose.model('User', UserSchema);

Step 4: Use the Method

Now, you can create a User instance and use the defined methods.

javascript
let 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.

2024年6月29日 12:07 回复

你的答案