티스토리 뷰

Mongoose/schemas

Indexes

mongoT 2020. 3. 9. 17:45

Mongoose에서 인덱스를 선언하는 방법은 2가지가 있다.

path level(또는 field level)에서 정의하는 법과 schema level에서 정의하는 법.

 

스키마를 정의하면서 field level에서 정의할 수 있고, schema정의가 끝나고 index() 메서드를 통해서 정의할 수도 있다. compound index를 만드려면 index() 메서드를 사용해야 한다.

  const animalSchema = new Schema({
    name: String,
    type: String,
    tags: { type: [String], index: true } // field level
  });

  animalSchema.index({ name: 1, type: -1 }); // schema level
  
  const Animal = mongoose.model('Animal', animalSchema);

application이 시작했을 때 Mongoose는 자동으로 schema에 정의된 index property에 대해서 db.animals.createIndex()를 실행한다.

Animal.on('index', function (err) {
    if (err) return console.error(err);
    console.log('index created!'); // 'index created!'
})

index가 잘 정의 되었는지 확인해보면.

문제는 node process가 시작될 때마다 이러한 index를 자동으로 만드는 작업이 상당한 성능 저하를 초래한다는 것이다.

개발 버전에서는 도움이 될 수도 있지만 배포 버전에서는 이러한 행동을 못하게 해야 한다.

mongoose가 자동으로 createIndex()를 호출하는 것을 막는 방법은 db레벨에서 global로 설정하는 법과 schema레벨에서 막는 방법 2가지가 있다. 

 

db레벨에서 막는 법:

// connected to db server
mongoose.connect('mongodb://localhost/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    autoIndex: false // diable autoIndex
});

schema레벨에서 막는 법:

const animalSchema = new Schema({
    name: String,
    breed: String,
    tags: { type: [String], index: true } // field level
}, { autoIndex: false }); // disable index

이렇게 option에 autoIndex false로 설정하면 index를 자동으로 만들지 않고 index 이벤트도 emit 되지 않는다.

 

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