Could you please explain in simple words what Instance methods are while using mongoose? Could you please explain in simple words what Instance methods are while using mongoose? mongoose mongoose

Could you please explain in simple words what Instance methods are while using mongoose?


A Mongoose modelschema declaration is more or less like a Class declaration, so it's more or less like this:

    class Person {        constructor (name, yearOfBirth, job) {            this.name = name;            this.yearOfBirth = yearOfBirth;            this.job = job;        }        calculateAge() {            var age = new Date().getFullYear - this.yearOfBirth;            console.log(age);        }    }    const john6 = new Person6('John', 1990, 'teacher');john6.calculateAge() // Returns age


It seems the docs have a very unintuitive way of explaining things. Let's go over the basics of creating a model, shall we?You define a schema -

var mongoose = require('mongoose');  var Schema = mongoose.Schema;  // any random Schema  var animal_SCHEMA = new Schema({    name:  String,    type: String  });

You can define your own methods that your model instances can use.

Taking the example from the docs, the way to create an instance method is -

animalSchema.methods.findSimilarTypes = function() {    return mongoose.model('Animal').find({ type: this.type }); //I omitted the callback for simplicity  };

Then, you make a model and may export it. Here I'm just creating the model.

var animal_MODEL = mongoose.model('Animals', animal_SCHEMA);

So now you created a model and an instance instance for the model instances, but where's the instance that will use it? Let's create one. This is how you normally create an instance of your model. Nothing new about it.

var newAnimal = new animal_MODEL({name:"Scobby", type:"Detective"}); // this can use findSimilarTypes

You're probably comfortable to create such new instances and save them, usually like -

const savedData = await newAnimal.save();

Ever wondered about the save() method? Well, that's an example of an instance method! Mongoose supplies save() by default along with a bunch of other methods, see the API docs.

They are called so because they only come with an instance of an object.

Every instance of a model you create has some built-in instance methods. The one you defined earlier, that's an instance method that is custom and made by you.Now, newAnimal can use this method.

In fact, all new instances you spawn for this model will have access to the findSimilarTypes method.

var badAnimal = new animal_MODEL({name:"Scrappy", type:"Trouble Maker"});var trouble_makers = badAnimal.findSimilarTypes();console.log(trouble_makers);