Whats the difference between instance and static methods in Mongoose?

tdd

#1

Question

What’s the difference between instance and static methods in Mongoose?

Answer

As we may recall from the Mongoose fundamentals lesson, static methods are methods that directly apply or interact with our model, for example when we wanted to retrieve one dinosaur document from the database we created a find by name static method:

DinosaurSchema.statics.findByName

it allowed us to go through the database and retrieve the document that matched the given condition (name)

In opposition, instance methods or appended methods created with Mongoose’s .methods() are known as document methods, since they are only applied per method, not for a database, for example the breed method in our dinosaur schema:

DinosaurSchema.methods.breed

we need to already have a dinosaur document to manipulate the count property with the breed method, once we have that document:

const dino = new Dinosaur({
        name: 'Stegosaurus',
        count: 3,
        risk: 'Low'
      });

we can call the method on it:

dino.breed();

which will increase the number in the count property by one.