What is the difference between methods and statics?
Mongoose API defines statics as
Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.
What exactly does it mean? What does existing directly on models mean?
Statics code example from documentation:
AnimalSchema.statics.search = function search (name, cb) {
return this.where('name', new RegExp(name, 'i')).exec(cb);
}
Animal.search('Rover', function (err) {
if (err) ...
})
mongoose Mongoose Schemas Schema Statics Schema Statics are methods that can be invoked directly by a Model (unlike Schema Methods, which need to be invoked by an instance of a Mongoose document). You assign a Static to a schema by adding the function to the schema's statics object.
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. Given the example Animal Model below: var AnimalSchema = mongoose. Schema({ name: String, type: String, hasTail: Boolean }); module.
Each Schema can define instance and static methods for its model.
An instance of a model is called a document. Creating them and saving to the database is easy. const Tank = mongoose. model('Tank', yourSchema); const small = new Tank({ size: 'small' }); small. save(function (err) { if (err) return handleError(err); // saved! }); // or Tank.
Think of a static
like an "override" of an "existing" method. So pretty much directly from searchable documentation:
AnimalSchema.statics.search = function search (name, cb) {
return this.where('name', new RegExp(name, 'i')).exec(cb);
}
Animal.search('Rover', function (err) {
if (err) ...
})
And this basically puts a different signature on a "global" method, but is only applied when called for this particular model.
Hope that clears things up a bit more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With