Modelのインスタンスはドキュメントに対応するものです。Mongooseではドキュメントに関する操作をModelのインスタンスメソッド・クラスメソッドとして持っており、独自のメソッドを定義することもできます。
インスタンスメソッド
// schemaを定義
var animalSchema = new Schema({ name: String, type: String });
// animalSchema の "methods" オブジェクトに関数を定義します
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
こうすると、全てのanimalインスタンスでfindSimilarTypes
メソッドが使えるようになります。
this
はModelのインスタンスを指します。
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function (err, dogs) {
console.log(dogs); // woof
});
既存のメソッドをオーバーライドすると、予期しない不具合が発生する可能性があります。
クラスメソッド(Statics)
// animalSchema の "statics" オブジェクトに関数を定義します
animalSchema.statics.findByName = function (name, cb) {
this.find({ name: new RegExp(name, 'i') }, cb);
}
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
console.log(animals);
});
this
はModelを指します。
まとめ
- インスタンスメソッドは
schema.methods
- クラスメソッドは
schema.statics
にそれぞれ関数を定義する!