Mongoose 'static' methods vs. 'instance' methods

statics are the methods defined on the Modelmongoose

methods are defined on the document (instance).ui

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

// 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 document instances have a findSimilarTypes method available to it.spa

And then:code

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

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

 

You might do,  it

Animal .  Modal
Animal.findByName('fido', function(err, fido){
    // fido => { name: 'fido', type: 'dog' }
});

 

And then you might use the document instance fido to doio

fido .  documentconsole

fido.findSimilarTypes(function(err, dogs){
    // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
});
相關文章
相關標籤/搜索