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

我相信这个问题类似于 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 中的 staticsmethods 对象是什么?有什么区别?为什么我要使用其中一个?

最佳答案

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.constructorthis.model('Animal')),但它不会有一个不使用实例的任何属性的实例方法是有意义的(至少在这种情况下)。 (感谢 @AaronDufour 指出这一点)

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

相关文章:

python - 如何使用 PyMongo 在 MongoDB 中创建新数据库?

mongodb - 如何通过 Docker 在 MongoDB 上启用身份验证?

mongodb - 在 MongoDB 中查找最大的文档大小

mongodb - Mongoose 中权重的全文搜索

java - 从 JSON 字符串创建 BSON 对象

mongodb - 如何删除 Mongo 中已弃用的字段?

node.js - 为什么我们应该使用 mongoose ODM 而不是直接使用 Mongodb 和

mongodb - 如何在 Mongo 中描述一个集合?

python - 集合对象不是 PyMongo 的可调用错误

mongodb - 在 mongodb 中运行 javascript 脚本(.js 文件),包括 j