Mongoose'静态'方法与'实例'方法

Sta*_*tec 55 mongoose mongodb node.js

我相信这个问题与类似,但术语不同.从Mongoose 4 文档:

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

// 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);
}
Run Code Online (Sandbox Code Playgroud)

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

然后:

向模型添加静态方法也很简单.继续我们的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);
});
Run Code Online (Sandbox Code Playgroud)

在静态方法中,似乎每个动物实例都具有findByName可用的方法.架构中有什么staticsmethods对象?有什么区别,为什么我会使用一个而不是另一个?

lag*_*lex 68

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

你可能会这样做

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

然后你可以使用文档实例Animal.findByName来做

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

  • @laggingreflex 你的第二条评论是不正确的。你_可以_拥有`fido.findByName`,因为`fido`确实可以访问整个集合(通过`this.model('Animal')`)。但是,拥有不使用实例中任何属性的实例方法没有多大意义。 (2认同)