반응형
Mongoose/MongoDB에서 멀티필드 인덱스 생성
Mongoosejs에서 다중 필드 인덱스를 만드는 방법에 대한 문서를 찾고 있지만, 아무 소용이 없습니다.특히 색인화 및 고유화해야 하는 두 개의 필드가 있습니다.두 필드를 함께 인덱싱하는 mongoose 스키마의 예는 무엇입니까?
당신이 전화하세요.index메서드 온 유저Schema여기에 나타낸 바와 같이 그것을 하는 것을 반대합니다.고객님의 경우 다음과 같습니다.
mySchema.index({field1: 1, field2: 1}, {unique: true});
복합 인덱스를 생성할 때 스키마 수준에서 인덱스를 정의해야 합니다.
animalSchema.index({ name: 1, type: -1 });
참고 자료: http://mongoosejs.com/docs/guide.html#indexes
import { Schema, Document, model } from 'mongoose';
import { IUser } from './User';
import { IMood } from './Mood';
import { ILocation } from './Location';
export interface IUserMoodLocation extends Document {
userId?: IUser['_id'];
moodId?: IMood['_id'];
locationId?: ILocation['_id'];
}
const UserMoodLocationSchema: Schema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
},
moodId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Mood'
},
locationId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Location'
}
});
UserMoodLocationSchema.index(
{ userId: 1, moodId: 1, locationId: 1 },
{ unique: true }
);
export const UserMoodLocation = model<IUserMoodLocation>(
'UserMoodLocation',
UserMoodLocationSchema
);
Following command can be used to create compound index for nested json:
db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1})
Mongo json structure is like :
{"_id":"648738"
"account": {
"id": "123",
"customerId": 7879,
"name": "test"
..
..
}
}
샘플 데이터로 테스트해 보았습니다만, 정상적으로 동작하고 있습니다.
참고로, 받아들여진 답변은 틀렸습니다.https://stackoverflow.com/a/52553550/129300에 따르면 필드명은 작은 따옴표로 묶어야 합니다.즉, 다음과 같습니다.
mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
해피데이!
언급URL : https://stackoverflow.com/questions/12573753/creating-multifield-indexes-in-mongoose-mongodb
반응형
'IT' 카테고리의 다른 글
| React 내부에 Polymer를 사용할 수 있습니까? (0) | 2023.03.14 |
|---|---|
| ng-change는 새로운 가치와 원래 가치를 가져옵니다. (0) | 2023.03.14 |
| 타이프스크립트 반응 - 'react-materialize' 모듈에 대한 선언 파일을 찾을 수 없습니다.'path/to/module-name.module'에는 암묵적으로 임의의 유형이 있습니다. (0) | 2023.03.09 |
| JSON.NET JsonConvert 와NET JavaScript Serializer (0) | 2023.03.09 |
| Material-UI RaisedButton 링크를 외부 URL에 연결하려고 해도 실패합니까? (0) | 2023.03.09 |