node.js 猫鼬“静态”方法与“实例”方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29664499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:38:55  来源:igfitidea点击:

Mongoose 'static' methods vs. 'instance' methods

node.jsmongodbmongoose

提问by Startec

I believe this question is similar to this onebut the terminology is different. From the Mongoose 4 documentation:

我相信这个问题类似于这一个,但术语是不同的。从猫鼬 4文档

We may also define our own custom document instance methods too.

我们也可以定义我们自己的自定义文档实例方法。

// define a schema
var animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

Now all of our animal instances have a findSimilarTypes method available to it.

现在我们所有的动物实例都有一个可用的 findSimilarTypes 方法。

And then:

进而:

Adding static methods to a Model is simple as well. Continuing with our animalSchema:

向模型添加静态方法也很简单。继续我们的动物模式:

// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
  return this.find({ name: new RegExp(name, 'i') }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
  console.log(animals);
});

It seems with static methods each of the animal instances would have the findByNamemethod available to it as well. What are the staticsand methodsobjects in a Schema? What is the difference and why would I use one over the other?

似乎使用静态方法,每个动物实例也都有findByName可用的方法。Schema中的staticsmethods对象是什么?有什么区别,为什么我要使用一个而不是另一个?

回答by laggingreflex

staticsare the methods defined on the Model. methodsare defined on the document (instance).

statics是在模型上定义的方法。methods在文档(实例)上定义。

You might use a staticmethod like Animal.findByName:

您可能会使用静态方法,例如Animal.findByName

const fido = await Animal.findByName('fido');
// fido => { name: 'fido', type: 'dog' }

And you might use an instance methodlike fido.findSimilarTypes:

你可能会使用一个实例方法,fido.findSimilarTypes

const dogs = await fido.findSimilarTypes();
// dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]

But you wouldn't do Animals.findSimilarTypes()because Animals is a model, it has no "type". findSimilarTypesneeds a this.typewhich wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

但是你不会这样做,Animals.findSimilarTypes()因为 Animals 是一个模型,它没有“类型”。findSimilarTypes需要一个this.type在 Animals 模型中不存在的属性,只有一个文档实例会包含该属性,如模型中所定义。

Similarly you wouldn't1 do fido.findByNamebecause findByNamewould need to search through all documents and fidois just adocument.

同样,您不会这样做,fido.findByName因为findByName需要搜索所有文档并且fido只是一个文档。

1Well, technically you can, because instance does have access to the collection (this.constructoror this.model('Animal')) but it wouldn't make sense (at least in this case) to have an instance method that doesn't use any properties from the instance. (thanks to @AaronDufourfor pointing this out)

1好吧,从技术上讲,您可以,因为实例确实可以访问集合(this.constructorthis.model('Animal')),但是拥有一个不使用实例中的任何属性的实例方法是没有意义的(至少在这种情况下)。(感谢@AaronDufour指出这一点)

回答by MR EXCEL

Database logic should be encapsulated within the data model. Mongoose provides 2 ways of doing this, methods and statics. Methods adds an instance method to documents whereas Statics adds static “class” methods to the Models itself.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:

数据库逻辑应该封装在数据模型中。Mongoose 提供了两种方法来做到这一点,方法和静态。方法向文档添加实例方法,而静态向模型本身添加静态“类”方法。静态关键字定义模型的静态方法。不会在模型的实例上调用静态方法。相反,他们在模型本身上被调用。这些通常是实用程序函数,例如创建或克隆对象的函数。像下面的例子:

const bookSchema = mongoose.Schema({
  title: {
    type : String,
    required : [true, 'Book name required']
  },
  publisher : {
    type : String,
    required : [true, 'Publisher name required']
  },
  thumbnail : {
    type : String
  }
  type : {
    type : String
  },
  hasAward : {
    type : Boolean
  }
});

//method
bookSchema.methods.findByType = function (callback) {
  return this.model('Book').find({ type: this.type }, callback);
};

// statics
bookSchema.statics.findBooksWithAward = function (callback) {
  Book.find({ hasAward: true }, callback);
};

const Book = mongoose.model('Book', bookSchema);
export default Book;

for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/

更多信息:https: //osmangoni.info/posts/separating-methods-schema-statics-mongoose/