gpt4 book ai didi

node.js - Mongoose 'static' 方法与 'instance' 方法

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:31 25 4
gpt4 key购买 nike

我相信这个问题类似于this one但术语不同。来自 Mongoose 4 documentation :

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.

然后:

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);
});

似乎使用静态方法,每个动物实例也将具有可用的 findByName 方法。架构中的staticsmethods 对象是什么?有什么区别以及为什么我要使用其中一种而不是另一种?

最佳答案

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

您可以使用静态方法,例如Animal.findByName:

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

您可以使用实例方法,例如fido.findSimilarTypes:

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

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

同样,您也不会执行 fido.findByName,因为 findByName 需要搜索所有文档,而 fido 只是一个文档。

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

关于node.js - Mongoose 'static' 方法与 'instance' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com