What is the difference between methods and statics in Mongoose?

前端 未结 2 566
-上瘾入骨i
-上瘾入骨i 2021-01-02 01:30

What is the difference between methods and statics?

Mongoose API defines statics as

Statics are pretty much the same as methods but allow for defini         


        
2条回答
  •  粉色の甜心
    2021-01-02 01:54

    It seems like

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

    whereas

    'static' adds static "class" methods to the Models 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);
    });
    

提交回复
热议问题