【问题标题】:What is the difference between methods and statics in Mongoose?Mongoose 中的方法和静态有什么区别?
【发布时间】:2014-06-18 23:17:33
【问题描述】:

方法和静态有什么区别?

Mongoose API 将静态定义为

Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.

具体是什么意思?直接存在于模型上是什么意思?

文档中的静态代码

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

Animal.search('Rover', function (err) {
  if (err) ...
})

【问题讨论】:

  • 方法对模型的实例进行操作。静态函数仅充当辅助函数,可以执行您想要的任何操作,包括集合级别的搜索。它们不依赖于模型的实例。
  • 但是方法也是在模型上定义的,并且适用于该模型的所有实例。不是吗?
  • 是的,它们都是在模型上定义的。重要的是他们“采取”​​行动。
  • 如果模型与实例绑定,那么为什么我可以使用“this”以静态方式访问模型?

标签: node.js mongoose


【解决方案1】:

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

这基本上在“全局”方法上放置了不同的签名,但仅在针对此特定模型调用时才应用。

希望能把事情弄清楚一点。

【讨论】:

  • 在这种情况下,AnimalSchema.search 也会起作用吗?如果不是,是因为搜索已经在所有模型上定义为一种全局方法吗?是不是类似于Java - Overriding where subclass redefined the method by the super class.
  • @raju 这就是我们的意图。可以调用通常适用于“模型”的任何其他方法。你可以“建模”自定义方法。 “静态”表示“调用它而不是..”,因此它本质上是一个覆盖,其中 this 是“超级”。
【解决方案2】:

好像

'method' 将实例方法添加到由模型构造的文档中

而

'static' 向模型本身添加静态“类”方法

来自文档:

Schema#method(method, [fn])

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

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

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

Schema#static(name, fn)

向从此架构编译的模型添加静态“类”方法。

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

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2013-07-21
    • 2012-11-02
    • 2011-07-11
    • 1970-01-01
    • 2011-01-27
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多