Today I Learned

MongoDB populate

c3epmos 2020. 1. 9. 18:07

문제

SQL의 JOIN 문과 같이 참조 collection의 정보를 조회해야 한다.

 

해결

mongodb에서 제공하는 populate 메소드를 이용해 collection 안에 다른 collection 정보들을 함께 담아서 전송할 수 있다.

 

model/Board.js

참조할 속성에는 'ref'를 이용해 표시해야 한다. 그래야 어떤 모델을 참조할지 알 수 있다.

 

routes/Boards/index.js

find() 메소드 후에 populate 메소드를 실행하고, 입력 인자 안에는 참조에 필요한 속성명을 넣는다.

 

출처

https://mongoosejs.com/docs/populate.html

 

Mongoose v5.8.5: Query Population

Populate MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections. Population is the process of automatically replacing th

mongoosejs.com