Mongoose中的方法和静态方法有什么区别? [英] What is the difference between methods and statics in Mongoose?

查看:76
本文介绍了Mongoose中的方法和静态方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the difference between methods and statics?

猫鼬API将静态定义为

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?

文档中的静态代码

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

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

推荐答案

static视为现有"方法的替代".因此,几乎直接来自可搜索的文档:

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.

这篇关于Mongoose中的方法和静态方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆