How to Add Static Methods with Mongoose

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you’re using the popular Schema-Model based library Mongoose to interact with MongoJS from NodeJS then this article will provide you a basic understanding of static methods. If you don’t know what a static method is, we’ll define them in the next section, and then we’ll show you a couple examples that will demonstrate where to utilize them because it comes in extremely handy in numerous situations.

Static Methods

Static methods are methods that run from the context of the entire Model and not a specific instance of that Model (docuement) like a specific User or a specific Product. Static methods are the counterpart to instance methods which operate on a specific instance like a User or Product.

The context of what you want to do will typically dictate whether you want a static or an instance method. For example if you want to get the full name of a User, that’s something that should only involve one user and so would be an instance method, whereas a method to get the top ten most active users is more of a query for the entire class so would be a static method.

If you’re not clear we’ll show you a couple examples in this next section that should clear up any confusion.

Demo Examples

In our first example we want you to pay particularly close attention to the syntax. In this example we have a schema for users that will get retrieve all the users. Notice that this would not be appropriate functionality as an instance method because it does not just involve a specific user. It is though perfect for a static method. Let’s take a look at the code:

1
2
3
4
5
6
7
8
9
10
11
userSchema.statics.getUsers = function() {
  return new Promise((resolve, reject) => {
    this.find((error, docs) => {
      if(error) {
        console.error(error)
        return reject(error)
      }
      resolve(docs)
    })
  })
}

Notice how we created a function on the .statics object on our schema. The function uses the .find() method to get all users in the database. In this case the this keyword refers to the entire schema and not just an instance.

Now let’s see how we’d use it:

1
2
3
4
5
6
7
UserModel.getUsers()
  .then(docs => {
    console.log(docs)
  })
  .catch(err => {
    console.error(err)
  })

Notice how simple and intuitive this function call is UserModel.getUsers(). This is easy to read and makes sense. This is one of the big benefits of using these static methods as it often makes for some clear code.

Let’s show another example to cement our understanding.

In this example we have a schema representing a grocery store product and we’ll have a custom static method that finds any products with a certain brand. Let’s take a look at the productSchema first:

1
var productSchema = new Schema({ name: String, brand: String });

Now let’s add a custom static method:

1
2
3
  productSchema.statics.findByBrand = function(brandName) {
    return this.find({ brand: new RegExp(brandName, 'i') });
  };

We used a regular expression to search all our products for any brands that match regardless of upper or lowercase.

Now let’s see how to use it:

1
2
3
4
  var Product = mongoose.model('Product', productSchema);
  Product.findByBrand('DemoBrand', function(err, products) {
    console.log(products);
  });

Conclusion

We hope this short tutorial acquainted you with static methods in Mongoose and the associated syntax and functionality. We hope you can see all the possibilities that static methods open up and that you can apply them where they fit within your specific application. We hope you also see how clean and intuitive they can make your code that interacts with the database. If you found this type of functionality useful you might want to look the counterpart of static methods, instance methods. If you have any questions or feedback please don’t hesitate to reach out to us.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.