6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mongooseのモデルに独自メソッドを作成する

Posted at

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メソッドが使えるようになります。
thisModelのインスタンスを指します。

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

thisModelを指します。

まとめ

  • インスタンスメソッドは schema.methods
  • クラスメソッドは schema.statics

にそれぞれ関数を定義する!

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?