-
MongoDB populateToday I Learned 2020. 1. 9. 18:07
문제
SQL의 JOIN 문과 같이 참조 collection의 정보를 조회해야 한다.
해결
mongodb에서 제공하는 populate 메소드를 이용해 collection 안에 다른 collection 정보들을 함께 담아서 전송할 수 있다.
model/Board.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters// board 스키마를 정의한다. var boardSchema = new Schema({ // 작성자 정보를 보여주기 위해 참조한다. user_id: { type: ObjectId, ref: 'User' }, title: String, content: String, active: Number, // 누가, 얼마나 '좋아요' 했는지 확인하기 위해 참조한다. likes: [{ type: ObjectId, ref: 'User' }], // 게시글에 달린 댓글들을 보여주기 위해 참조한다. comments: [{ type: ObjectId, ref: 'Comment' }] }); 참조할 속성에는 'ref'를 이용해 표시해야 한다. 그래야 어떤 모델을 참조할지 알 수 있다.
routes/Boards/index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters// 전체 게시글 조회 라우트 router.get('/', async (req, res) => { /* populate 메소드는 reference 속성을 이용해 다른 collection으로부터 정보들을 가져오는 기능을 수행한다. 입력 인자로는 기준이 될 속성 값을 넣어야 한다. */ Board.find().populate('comments').populate('user_id').exec((err, result) => { if(err){ console.log(err); return res.status(statusCode.INTERNAL_SERVER_ERROR).send(utils.successFalse(responseMessage.BOARD_READ_ALL_FAIL)); } return res.status(statusCode.OK).send(utils.successTrue(responseMessage.BOARD_READ_ALL_SUCCESS, result)); }); }); 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
'Today I Learned' 카테고리의 다른 글
Sequelize (0) 2020.01.10 MongoDB 다른 model의 require 문제 (0) 2020.01.10 getQuery (0) 2020.01.08 mongoose middleware 제작 (0) 2020.01.08 VS Code 특정 단어 한번에 수정하기 (0) 2020.01.07