티스토리 뷰

Mongoose/schemas

Statics

mongoT 2020. 3. 9. 15:57

Model에는 instance method 말고도 static functions가 있다.

 

잠깐 설명을 하자면 javascript 클래스에는 static이라는 개념이 있다.

일반적으로 method를 클래스에 선언하면 그 method의 this는 인스턴스에 바인딩된다.

static method에서 this는 클래스 그 자체에 바인딩된다.

 

schema 정의.

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

static method 정의.

// Assign a function to the "statics" object of our animalSchema
    animalSchema.statics.findByName = function (name) {
        console.log(this); // Model { Animal }
        return this.find({ name: new RegExp(name, 'i') });
    };

 

instance method와 마찬가지로 staic()로 정의 가능.

// Or, equivalently, you can call 'animalSchema.static()'.
    animalSchema.static('findByBreed', function (breed) {
        return this.find({ breed });
    })

model()로 컴파일 후 documents 2개 저장.

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

    let dog = new Animal({ name: 'fido', breed: 'Jindo' });
    let dog2 = new Animal({ name: 'mido', breed: 'Poodle' });
    await dog.save();
    await dog2.save();

Animal클래스에서 실행.

let animals = await Animal.findByName('fido');
animals = animals.concat(await Animal.findByBreed('Poodle'));
console.log(animals);
// [
//   {
//     _id: 5e65e6acf572ba594ced0828,
//     name: 'fido',
//     breed: 'Jindo',
//     __v: 0
//   },
//   {
//     _id: 5e64982c2a335b59e4918896,
//     name: 'mido',
//     breed: 'Poodle',
//     __v: 0
//   }
// ]

실제로 보면 Animal 클래스에 property로 정의되어있는 것을 알 수 있다.

    console.log(Animal.prototype.hasOwnProperty('findByBreed')); // false
    console.log(Animal.hasOwnProperty('findByBreed')); // true

    // 인스턴스에서 접근불가
    console.log(dog.findByName); // undefined

 

주의 점: ES6문법의 arrow function을 쓰지 말 것.(this 바인딩을 다르게 해석.)

 

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

git 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
Instance method  (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
글 보관함