"@nestjs/mongoose": "^8.0.1",
"mongoose": "^5.13.9",
populate
method를 이용하는데, 이와 관련해서 mongoose 버전이 6 이상인 경우, nestjs/mongoose 버전 8 이상인 것과 호환이 잘 안된다는 내용이 있었다.imports: [ MongooseModule.forFeature([
{ name: Cat.name, schema: CatSchema },
{ name: Comments.name, schema: CommentsSchema },
])
], // DB Query 작업을 위해, schema import | Authmodule 순환참조
1. 관게설정
_CatSchema.virtual('comments', {
// 연동되는 스키마와 식별자를 지정
// cats의 _id === comments의 info를 엮음.
ref: 'comments',
localField: '_id', // B테이블의 관계 식별자
foreignField: 'info', // A테이블의 관계 식별자
});
_CatSchema.set('toObject', { virtuals: true });
_CatSchema.set('toJSON', { virtuals: true });
export const CatSchema = _CatSchema;
----
2. virtual field 등록
onst options: SchemaOptions = {
timestamps: true, // DB에서 스키마 생성 시 일자를 출력
};
@Schema(options)
export class Cat extends Document {
readonly comments: Comments[] // Comments는 CommentSchema 객체이다.
}
populate
메소드를 이용한다.const comments = mongoose.model('comments', CommentsSchema); // du연결한 schema 이름
const data = await this.catModel.find().populate('comments', comments); // virtual field 이름 명시해야함.
return data;
comments.find(
{ info: { '$in': [ ObjectId("631359b781bd8128c4504cae"), ObjectId("631359c181bd8128c4504cb1") ] }},
{ projection: {} })
"data": [
{
"name": "레드",
"comments": []
},
{
"name": "블루",
"comments": []
}
]
}
await this.commentModel.create(
{ author: user._id, content: comments.content,
info: mongoose.Types.ObjectId(id) });
즉, mongoDB를 이용하면서, 관계식별자로 ObjectId를 사용하는 경우, 각 관계식별자에 Type이 ObjectId 타입으로 잘 들어가 있는지 꼼꼼히 확인해야한다...!