댓글을 같이 나오게끔 만들고 싶을 때,

댓글까지 나오게

위와 같이 하고 싶다면 아래와 같이 진행하면 된다.

cats.schema.ts 수정

{
  readonly comments: Comments[];
}
...


_CatSchema.virtual('readOnlyData').get(function (this: Cat) {
  return {
    id: this.id,
    email: this.email,
    name: this.name,
    imgUrl: this.imgUrl,
    comments: this.comments,
  };
});

_CatSchema.virtual('comments', {
  ref: 'comments',
  localField: '_id',
  foreignField: 'info',
});
_CatSchema.set('toObject', { virtuals: true });
_CatSchema.set('toJSON', { virtuals: true });

export const CatSchema = _CatSchema;

위와 같이 만들어주고

cats.repository.ts

async findAll() {
  const CommentsModel = mongoose.model('comments', CommentsSchema);

  const result = await this.catModel
    .find()
    .populate('comments', CommentsModel);

  return result;
}

위와 같이 설정해주면, 핵심은 populate 를 써주면, 해당하는 collection 값들을 같이 가져와준다. RDB에서의 JOIN 과 같은 역할을 해주는 듯.