In Mongoose, models are derived from Schema. You can define instance methods and static methods on the Schema. Instance methods operate on model instances (i.e., documents), while static methods operate directly on the model.
The following are the steps to define instance methods and static methods:
Instance Methods
To define instance methods in a Mongoose model, add functions to the methods property of the Schema. For example, suppose we have a user model and we want to add an instance method to validate a password:
javascriptconst mongoose = require('mongoose'); const bcrypt = require('bcrypt'); // Define the user's Schema const userSchema = new mongoose.Schema({ username: String, passwordHash: String, }); // Define an instance method to validate the password userSchema.methods.validatePassword = function(password) { return bcrypt.compare(password, this.passwordHash); }; // Create the model const User = mongoose.model('User', userSchema); // Use the instance method const user = new User({ username: 'exampleUser', passwordHash: bcrypt.hashSync('myPassword', 10), }); user.validatePassword('myPassword').then(isMatch => { console.log(isMatch ? 'Password is valid!' : 'Password is invalid.'); });
In this example, we use bcrypt to validate the password. We add an instance method named validatePassword to userSchema so that it can be called on any instance of the User model.
Static Methods
Static methods are defined as functions on the statics property of the Schema. They are attached to the model constructor, not to model instances. Here is an example of defining a static method:
javascript// Define a static method to find a user userSchema.statics.findByUsername = function(username) { return this.findOne({ username: username }); }; // Create the model const User = mongoose.model('User', userSchema); // Use the static method User.findByUsername('exampleUser').then(user => { console.log(user); });
In this example, we add a static method named findByUsername to userSchema, which can be called directly on the User model to find a user by username.
When defining methods in Mongoose models, ensure to use function declarations instead of arrow functions, as arrow functions do not bind the this keyword, while traditional function declarations allow you to correctly access the document instance (this) within the method.