What are methods and statistics in mongoose ?

Athira V Ajit
3 min readFeb 15, 2021

Most of us would have worked with or if not heard of mongoose a popular object data modeling (ODM) library for Mongodb.

The basic CRUD operations are quiet familiar to each one of us. In case you are some quiet new to the mongoose world check out the following link to get a better understanding of mongoose in general.

If you are someone from the mongoose world lets dive right in to our topic for today.

What are methods and statistics in mongoose ?

Photo by Mathew Schwartz on Unsplash

These help us in defining our basic database functions thus helping us to write concise code in our routers (in case of nodejs) or in functions.

Statistics and methods are quiet similar to each other with only difference being statics are functions you call on the whole model whereas methods are functions you call on a particular instance.

Lets see a set of examples to gain a better understanding of the topic.

Firstly create a user model of similar format.

Here I have created a schema method for password generation (generatePassword) and a schema statistics(emailIdAlreadyTaken) for email validity.

In the below gist I have demonstrated how to call the methods function.

Similarly we can creates methods for different cases, like converting a particular field to uppercase, lowercase so on and so forth.

Now lets move on to schema statics.

Photo by Joshua Newton on Unsplash

By viewing the above set of code , you might be wondering why would I use this.🤔

I could have just written these operations inside my JS function or router.🙄

You are exactly right in a way. These won’t make much sense if you are working on a relative small project or with a consistent set of contributors(Though I wouldn’t say you can’t use it in small project, you very well could). But imagine scenarios where you have many lines of code, many database operations then in those scenarios these come in handy because the person who is going to come in new to the project need not figure out why you used that function. He could very well just see generatePassword, and understand “Alright ! These set of operations are for generating the password💡”. Pretty straight forward right. Similarly in cases where you have the same database operations repeated in more than one function/router this could be your pretty solution.🤗

If you have reached her, thanks a lot for being patient🙈. Hoping you were able to retrieve some useful information from this article. If you are some who has never tried these, do try it out and let me know in comments the scenarios where you felt these methods helped you create cleaner code😍. In case you have already made use of these do comment the different scenarios were you have used these methods.

Happy learning !!!!!!!!! 👋

Also lets connect on LinkedIn

Feel free to check my github repo as well

--

--