티스토리 뷰

Mongoose/schemas

Instance method

mongoT 2020. 3. 9. 15:20

documents는 Model 클래스에 instance들이다.

저장한 data 이외에도 많은 built-in-instance methods를 가지고 있다.

물론 우리가 custom methods를 만들 수도 있다.

 

schema 인스턴스에  methods 프로퍼티에 findSimilarTypes라는 instance method를 정의해 준다.

const animalSchema = new Schema({ name: String, type: String, breed: String });

// overwritting a default mongoose doucment method may lead to unpredictable results.
animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

그리고 실제 mongoose와 model()를 통해 compile 해주고

let Animal = mongoose.model('Animal', animalSchema);

document 하나를 만든 후 save()하고 findSimilarTypes()로 방금 저장한 document와 같은 type을 가지고 있는 documents들을 찾는다.

const dog = new Animal({ type: 'dog' });

dog.save((err, dogs) => {
  if (err) return console.error(err);
  console.log(dogs);
  // { _id: 5e65dd719cff0d588c82bd72, type: 'dog', __v: 0 }

  dog.findSimilarTypes(function (err, dogs) {
    if (err) return console.error(err);
    console.log(dogs); 
    // [ { _id: 5e65dd719cff0d588c82bd72, type: 'dog', __v: 0 } ]
  });
});

이 instance method들은 model.prototype에 정의되는 것이기 때문에 instance인 document에서 쓸 수 있는 것이다.

console.log(dog.hasOwnProperty('findSimialrTypes')); // false
console.log(Animal.prototype.hasOwnProperty('findSimilarTypes')); // true

 

인스턴스 메서드를 사용할 때 주의점:

 

- default mongoose document method를 overwritting하면 예상치 못한 결과를 초래 할 수 있다.

- Schemas.methods 객체에 직접적으로 정의하지 않고 Schemas.method() helper를 이용해서 정의할 수 있다.

- ES6문법인 arrow function은 사용하지 말 것.(this를 다르게 바인딩하기 때문)

 

 

공식 레퍼런스: https://mongoosejs.com/docs/guide.html

Github Repository: https://github.com/taeheongo/MongoDB

'Mongoose > schemas' 카테고리의 다른 글

aliases  (0) 2020.03.09
Virtuals  (0) 2020.03.09
Indexes  (0) 2020.03.09
Query Helpers  (0) 2020.03.09
Statics  (0) 2020.03.09
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함