Statics and Methods in Mongoose

Statics and Methods in Mongoose

Before we start, let us first create a basic User model using Mongoose.

const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
    email: {
            required: true,
            type: String
    },
    password: {
            required: true,
            type: String
    }
});

// define all statics and methods here

const User = mongoose.model("user", userSchema);

Statics

First of all, let's talk about statics. Statics are functions defined in the user model which can be used on the whole model. Take a look at the example below :

userSchema.statics.emailExists = async function(email) {
    const user = await User.findOne({email: email});
    if (user) {
        return true;
    } else {
        return false;
    }
}

In the above example, we created a function which checks if an email address is already taken or not. Now, if we want to use it in our server, the code would look like the follows :

const emailTaken = User.emailExists("name@example.com");
if (emailTaken) {
    console.log("Email is already taken.")
}

Look in the above code how the function is being used on the User model, and not on a single instance or object in the collection.

Methods

Now, let's talk about methods in Mongoose. Methods are similar to statics, except that methods can be used on a single instance/object, unlike statics which can be used on the entire model. Let us take another example to understand this better :

const bcrypt = require("bcrypt");
userSchema.methods.encryptPassword = async function() {
    this.password = await bcrpyt.hash(this.password, 10);
}

Now, if you want to use this function, you can do so only by calling it on an instance :

const newUser = new User({
    email,
    password
});

newUser.encryptPassword();

As you can see, the function here is called on the object that we are creating, rather than on the entire User model as in the case of statics.

NOTE: We can use as many Methods on an object as we need, but only before we save the document, i.e. all Methods should be used before calling newUser.save();

Benefits

Let me tell you the most useful function of Statics and Methods: to write concise code in routers(Node.js) or in functions.

Now, you may wonder that you can do all these things in the router/function as well, so why would you need these Statics and Methods. And you would be right! But only for small projects. When a large project is being built, concise code is a must for a good and readable code. And the person reading your code can understand what encryptPassword() is doing without having to check its code, while it would be pain to look at the whole encrypting process in the main file instead.

If you read this far, thank you for your patience 😁😁. Hope you got to learn something new from here. Do try these out and talk in the comments about how you feel after using theseπŸ˜„.

Also, do connect with me on LinkedIn here:

https://www.linkedin.com/in/amartya-chowdhury-32996628b/

(Cover photo: https://mongoosejs.com/docs/typescript/statics-and-methods.html)

Β