'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) ...
})


Solution 1:[1]

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.

Solution 2:[2]

It seems like

'method' adds an instance method to documents constructed from Models

whereas

'static' adds static "class" methods to the Model itself

From the documentation:

Schema#method(method, [fn])

Adds an instance method to documents constructed from Models compiled from this schema.

var schema = kittySchema = new Schema(..);

schema.method('meow', function () {
  console.log('meeeeeoooooooooooow');
})

Schema#static(name, fn)

Adds static "class" methods to Models compiled from this schema.

var schema = new Schema(..);
schema.static('findByName', function (name, callback) {
  return this.find({ name: name }, callback);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neil Lunn
Solution 2 Joundill