13. Static and Instance Methods


Mongoose allows instance methods and static methods to be defined in a schema.  An instance method is a method that is called on an instance of the model (a document), whereas a static method is a method that is called on the Model itself.  Both types of methods have access to an object named this, however when used in an instance method this holds a reference to the instance (document) and when used in a static method this is a reference to the model itself.

In the example below we show a schema that defines an instance method named setToken and a static method named getUserByUsername.

import { model, Schema } from 'mongoose'

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
  },
  token: String
})

userSchema.methods.setToken = function(newToken) {
  // below this refers to the document on which setToken is called
  return this.token = newToken
}

userSchema.statics.getUserByUsername = async function(username) { 
  // this.findOne() (below) is equivalent to User.findOne() 
  return await this.findOne({ username }) 
}

const User = model('User', userSchema)

export default User

 

Below is a simple example where we show how we can use the static and instance methods.  First we call the static method to get a User document from the database by calling getUserByUsername.  Then, if we find a matching User document we set the document’s token field by calling setToken.

// call the User model's static getUserByUsername method
const user = await User.getUserByUsername("Joe")
    
if (user) {
    // call setToken on the user document
    user.setToken("test123")
    ....
}