What is the difference between methods and statics in Mongoose?

前端 未结 2 570
-上瘾入骨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 02:07

    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.

提交回复
热议问题