MongoDB : populate

김가영·2020년 10월 9일
0

Node.js

목록 보기
12/34
post-thumbnail

populate

ObjectId 를 객체로 치환해주는 것

  • ObjectId 를 쓰는 Schema 만들어주기
const {Schema} = mongoose;
const {Types : {ObjectId}} = Schema;

const commentSchema = new Schema({
    commenter : {
        type : ObjectId,
        required : true,
        ref : 'User',
    },
  ...
  • commenter 를 출력할 때 ObjectId 로 출력해주기
router.post('/', async (req, res, next) => {
    try{
        const comment = await Comment.create({
            commenter : req.body.id,
            comment : req.body.comment,
        });
        console.log(comment);
        const result = await Comment.populate(comment, {path : 'commenter'});
        res.status(201).json(result);

    }catch(err){
        console.error(err);
        next(err);
    }
});

Comment.populate(comment, {path : 'commenter'}) : comment 의 'commenter' path 의 ObjectId 를 Object 로 치환하게 된다.

profile
개발블로그

0개의 댓글