Mongoose的方法和静态有什么区别?

raj*_*aju 11 mongoose node.js

方法和静态之间有什么区别?

Mongoose API将静态定义为

Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.
Run Code Online (Sandbox Code Playgroud)

究竟是什么意思?直接在模型上存在什么意味着什么?

文档中的静态代码

AnimalSchema.statics.search = function search (name, cb) {
  return this.where('name', new RegExp(name, 'i')).exec(cb);
}

Animal.search('Rover', function (err) {
  if (err) ...
})
Run Code Online (Sandbox Code Playgroud)

Nei*_*unn 9

想象一下static"覆盖""现有"方法.所以直接来自可搜索的文档:

AnimalSchema.statics.search = function search (name, cb) {
   return this.where('name', new RegExp(name, 'i')).exec(cb);
}

Animal.search('Rover', function (err) {
  if (err) ...
})
Run Code Online (Sandbox Code Playgroud)

这基本上在"全局"方法上设置了不同的签名,但仅在调用此特定模型时应用.

希望能把事情搞清楚一点.


oba*_*bai 8

这好像是

' method '为从Models构造的文档添加实例方法

' static '为模型本身添加静态"类"方法

从文档:

Schema#方法(方法,[fn])

将实例方法添加到从此模式编译的模型构造的文档中.

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

schema.method('meow', function () {
  console.log('meeeeeoooooooooooow');
})
Run Code Online (Sandbox Code Playgroud)

架构#static(名称,fn)

向从此模式编译的模型添加静态"类"方法.

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