티스토리 뷰

Mongoose/schemas

Query Helpers

mongoT 2020. 3. 9. 16:13

Query Helper는 instance method와 유사하지만 mongoose queries에만 쓰이는 helper function이다.

Query Helper는 말 그대로 mongoose의 chainable 한 mongoose의 query builder API를 확장시켜주는 method다.

 

스키마를 정의.

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

query property에 query helper를 정의후 컴파일.

animalSchema.query.byName = function (name) {
    return this.where({ name: new RegExp(name, 'i') });
}

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

chainable 한 query 실행.

Animal.find().byName('fido').exec(function (err, animals) {
    console.log(animals);
});
// [
//   {
//     _id: 5e65e6acf572ba594ced0828,
//     name: 'fido',
//     breed: 'Jindo',
//     __v: 0
//   }
// ]

 

공식 레퍼런스: 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
Statics  (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
글 보관함