Mongoose 'static' methods vs. 'instance' methods

I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:

We may also define our own custom document instance methods too.

// define a schema
var animalSchema = new Schema({ name: String, type: String });


// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}

Now all of our animal instances have a findSimilarTypes method available to it.

And then:

Adding static methods to a Model is simple as well. Continuing with our animalSchema:

// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
}


var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
console.log(animals);
});

It seems with static methods each of the animal instances would have the findByName method available to it as well. What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?

41290 次浏览

statics are the methods defined on the Model. methods are defined on the document (instance).

You might use a static method like Animal.findByName:

const fido = await Animal.findByName('fido');
// fido => { name: 'fido', type: 'dog' }

And you might use an instance method like fido.findSimilarTypes:

const dogs = await fido.findSimilarTypes();
// dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]

But you wouldn't do Animals.findSimilarTypes() because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

Similarly you wouldn't¹ do fido.findByName because findByName would need to search through all documents and fido is just a document.

¹Well, technically you can, because instance does have access to the collection (this.constructor or this.model('Animal')) but it wouldn't make sense (at least in this case) to have an instance method that doesn't use any properties from the instance. (thanks to @AaronDufour for pointing this out)

Database logic should be encapsulated within the data model. Mongoose provides 2 ways of doing this, methods and statics. Methods adds an instance method to documents whereas Statics adds static “class” methods to the Models itself.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:

const bookSchema = mongoose.Schema({
title: {
type : String,
required : [true, 'Book name required']
},
publisher : {
type : String,
required : [true, 'Publisher name required']
},
thumbnail : {
type : String
}
type : {
type : String
},
hasAward : {
type : Boolean
}
});


//method
bookSchema.methods.findByType = function (callback) {
return this.model('Book').find({ type: this.type }, callback);
};


// statics
bookSchema.statics.findBooksWithAward = function (callback) {
Book.find({ hasAward: true }, callback);
};


const Book = mongoose.model('Book', bookSchema);
export default Book;

for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/

Well to me it doesn't mean add anythings by adding Mongoose in front of 'static' or even in front 'instance' keyword.

What I believe meaning and purpose of static is same everywhere, even it's also true for an alien language or some sort of driver which represents Model for building the block like another object-oriented programming. The same also goes for instance.

From Wikipedia: A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of data and behavior. The data and behavior comprise an interface, which specifies how the object may be utilized by any of various consumers[1] of the object.

Data is represented as properties of the object and behaviors are represented as methods of the object. For example, a Window object could have methods such as open and close, while its state (whether it is opened or closed at any given point in time) would be a property.

Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to static variables in that sense. An example would be a static method to sum the values of all the variables of every instance of a class. For example, if there were a Product class it might have a static method to compute the average price of all products.

Math.max(double a, double b)

This static method has no owning object and does not run on an instance. It receives all information from its arguments.[7]

A static method can be invoked even if no instances of the class exist yet. Static methods are called "static" because they are resolved at compile time based on the class they are called on and not dynamically as in the case with instance methods, which are resolved polymorphically based on the runtime type of the object.

https://en.wikipedia.org/wiki/Method_(computer_programming)

  • Use .statics for static methods.
  • Use .methods for instance methods.
//instance method
bookSchema.methods.findByType = function (callback) {
return this.model('Book').find({ type: this.type }, callback);
};


// static method
bookSchema.statics.findBooksWithAward = function (callback) {
Book.find({ hasAward: true }, callback);
};

statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.

statics belongs to the Model and methods belongs to an Instance

Static methods apply to the entire model on which they are defined whereas instance methods apply only to a specific document within the collection.

this in the context of a static method returns the entire model whereas this in the context of an instance method returns the document.

Lets say for example:

const pokemon = new mongoose.Schema({})
pokemon.statics.getAllWithType = function(type){
// Query the entire model and look for pokemon
// with the same type
// this.find({type : type})
}


pokemon.methods.sayName = function(){
// Say the name of a specific pokemon
// console.log(this.name)
}




const pokemonModel = mongoose.model('schema', pokemon)
const squirtle = new pokemonModel({name : "squirtle"})


// Get all water type pokemon from the model [static method]
pokemonModel.getAllWithType("water")


// Make squirtle say its name [instance method]
squirtle.sayName()

As everybody said, use methods when we want to operate on a single document, and we use statics when we want to operate on entire collection. But why?

Let's say, we have a schema:

var AnimalSchema = new Schema({
name: String,
type: String
});

now as mentioned in the docs, if you need to check the similar types of a particular document in the db you can do:

AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.model('Animal').find({ type: this.type }, cb);
};

Now, this here refers to the document itself. So, what that means is, this document doesn't knows which model it belongs to, because methods has nothing to do with the model defaultly, It's only for that particular document obj. But we can make it work with the model, using this.model('anyModelName').

Now why did we used methods in the case of finding similar types of animals?

For finding similar types of animals we must have an animal obj for which we'll find similar types of. That animal obj we have let's say: const Lion = await new Animal({name: Lion, type:"dangerous"}); Next, when we find similar types we need the Lion obj first, we must have it. So simply, whenever we need the help of a particular obj/document for doing something, We'll use methods.

Now here by chance we also need whole model to search slimier types, although it is not available directly in methods (remember this.modelName will return undefined). we can get it by setting this.model() to our preferred model, in this case Animal. That's all for methods.

Now, statics has the whole model at its disposal. 1)Let's say you want to calculate the total price (assume the model has a price field) of all Animals you'll use statics [for that you don't need any particular Animal obj, so we won't use method] 2)You want to find the animals which have yellow skin (assume the model has a skin field), you'll use statics. [ for that we don't need any particular Animal obj, so we won't use method]

eg:

 AnimalSchema.statics.findYellowSkin = function findSimilarType (cb) {
return this.find({ skin: "yellow" }, cb);
};

Remember, In methods this refers to the model so, this.modelName will return Animal (in our case).

but just like methods, here also we can (but we don't need to) set the model using.

AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.model('Animal').find({ skin: "yellow" }, cb);   //just like in methods
};

so as you can see both of statics and methods are very similar.

Whenever you have a document and you need something to do with that, use methods. Whenever you need to do something with the whole model/collection, use statics.