Backend/MongoDB

Mongoose Populate 사용하기

jellylucy 2023. 1. 30. 20:55

Populate 란

join과 유사한 개념이다.

Populate는 문서의 경로를 다른 컬렉션의 실제 문서로 자동으로 바꾸는 방법입니다.

= document의 필드값을 다른 collection 의 특정 document로 치환하는 과정이다.

Populate 관계 생성 방법

population은 참조 필드를 통해 이루어진다.

참조 관계는 스키마 생성 단계에서 지정해주면, 참조 대상은 collection이다.

-> 스키마 생성 단계에서 특정 필드가 어떤 collection을 참조할 것인지 명시해줘야 한다.

 

author필드

User collection을 참조하고 있다. (ref : 'User')

author의 값은 user 스키마를 따라야 하먀, 저장되는 값은 user의 ObjectId이다. (type: Schema.Types.ObjectId)

 

populate 을 사용한 스키마에서 하나의 document 생성하기

1. 먼저 user 스키마에서 하나의 document를 가져온다

const author = await User.findOne({name: "bohyeon"});

2. User를 populate하여 생성된 Post Schema에서 하나의 document 생성한다

await Post.create({
	title: 'bohyeon post',
	content: '안녕하세요',
	author: author
})

3. 출력하기

 

4. populate 함수를 통해 author 값 치환

await Post.findOne({title: 'bohyeon post'}).populate('author');


populate의 여러가지 활용법

// 기본
await Post.findOne({title: 'bohyeon post'}).populate('author');

// 원하는 key만 빼올 수 있다.
author = {path: 'authorId', select: '_id authorName shopKey shopType'}
await Post.findOne({title: 'bohyeon post'}).populate('author');

// 이중 populate
discountBook =       
	joinDiscount: {
        path: 'discount',
        populate: [
          {path: 'appliedItems.itemId', select: '_id itemName'}
        ]
      }
      
await Post.findOne({title: 'bohyeon post'}).populate('discountBook');