Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between methods and statics in Mongoose?

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) ...
})
like image 696
raju Avatar asked May 02 '14 09:05

raju


People also ask

What is static method in mongoose?

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.

What is method in mongoose?

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.

Can you define methods in Mongoose schema?

Each Schema can define instance and static methods for its model.

What is instance in mongoose?

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.


1 Answers

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.

like image 156
Neil Lunn Avatar answered Oct 16 '22 17:10

Neil Lunn