我相信这个问题类似于 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
方法。 Schema 中的 statics
和 methods
对象是什么?有什么区别?为什么我要使用其中一个?
最佳答案
statics
是模型上定义的方法。 方法
在文档(实例)上定义。
您可以使用 static 方法,例如 Animal.findByName
:
const fido = await Animal.findByName('fido');
// fido => { name: 'fido', type: 'dog' }
您可能会使用 method 实例,例如 fido.findSimilarTypes
:
const dogs = await fido.findSimilarTypes();
// dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
但你不会这样做 Animals.findSimilarTypes()
因为 Animals 是一个模型,它没有“类型”。 findSimilarTypes
需要一个在 Animals 模型中不存在的 this.type
,只有一个文档实例会包含模型中定义的该属性。
同样你不会做 fido.findByName
因为 findByName
需要搜索所有文档而 fido
只是 一个文件。
¹嗯,从技术上讲,您可以,因为实例确实可以访问集合(this.constructor
或 this.model('Animal')
),但它不会有一个不使用实例的任何属性的实例方法是有意义的(至少在这种情况下)。 (感谢 @AaronDufour 指出这一点)
关于node.js - Mongoose 'static' 方法与 'instance' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29664499/