[항해99] 44일차 몽구스 populate

IT/Bootcamp 항해99|2021. 7. 21. 01:17

항해 99

 

 

44일 차: 

 

 API마무리하는데 너무 오래 걸렸다.

일단 mongoose로 관계 설정 을해 주는 부분이 어제 배워놓고  실전에서 써보려고 하니깐 복잡한 게 많았다. 아니 복잡한 게 아니라 내가 멍청해서 쉬운 solution을 나 두고 인터넷 검색만 하루 종일 했다. 

기본적인 object , array개념도 모르는 것 같아서 슬픈 하루였다.  

object는 객체 , key :value.. 

array가  배열.    [apple, banana].. 

 

이번에 클론 코딩에서는 내가 백앤드 배포를 했는데, 생각보다 재밌었다.  이게 한 명이 aws배포를 하면 에러 메시지를 처리하고 파일 질라로 다시 업데이트를 하느라 배포한 사람이 주가 돼서 디버깅을 하는데, 저번 주에 하는 걸 보고 이걸 내가 할 수 있을지 걱정이었지만 생각보다 재밌었다.

 

 

post의 연결되는 코멘트 부분이  comments 하고 array로 감싸줬다. 

그래야 포스트에 해당하는 코멘트들이  array형태로 추가가 된다.

const mongoose = require("mongoose");
const { Schema } = mongoose
const getCurrentDate = require("../utils/moment")
const PostSchema = new Schema({

    _id: Schema.Types.ObjectId,
    postId: Number,
    userInfo: {

        firstName: String,
        lastName: String,
        profilePic: String,
    },
    content: {
        text: String,
        picture: String,
        createdAt: { type: Date, default: Date.now }
    },
    comments: [{
        type: Schema.Types.ObjectId,
        ref: 'Comment'

    }],

    like: {
        likeCnt: Number,
        userList: [{ firstName: String, lastName: String }]
    },


})

module.exports = mongoose.model('Post', PostSchema);

코멘트 작성 api

router.post('/', async (req, res) => {
    // comments writer info get from token
    const { commentText, postId } = req.body
    const _id = new mongoose.Types.ObjectId()
    const firstName = "skyler"
    const lastName = "Bang"

    try {
        const allComments = await Comment.find({})
        const commentId = allComments.length + 1
        const newComment = await Comment.create({ _id, postId, commentId, commentText, firstName, lastName });
        const post = await Post.findOne({ postId })
        if (post) {
            post.comments.push(newComment._id)
            post.save()
            //await Post.findOneAndUpdate(postId, { comments })
        }
        res.status(201).send({ commentId });
    } catch (err) {
        res.status(400).send(err);
    }
});

  포스트와 해당 포스트의 코멘트를 불러오는 api

populate안에 argument는 해당하는 스케마의 연결되는 부분.

위에서 post에서 연결되는 부분이  comments이니깐 comments로 써줘 야한다!!!


router.get("/", async (req, res) => {
    console.log(" Getting all the post API")
    const list = await Post.find({}).sort({ postId: -1 }).populate('comments')
    res.status(200).json(list)
})

 

 

- mongoose로 기능 구현을 하는 것까지 official document와 블로그 글들을 통해 잘 배워놓고

응용하는 부분에서 시간이 너무 많이 걸렸다.  아직까지도 기초가 모자라서 헤매는 것 같다. 

 

 

argument vs parameter?

https://www.google.com/search?q=argument+vs+parameter&sxsrf=ALeKk00CmZRyT9dvSkhzBnnTBCbUZTE11A%3A1626796426522&ei=ivH2YIu_H5rx-QbT7IX4Cg&oq=argument+vs+& gs_lcp=Cgdnd3Mtd2l6EAMYADIFCAAQkQIyBwgAEIcCEBQyAggAMgIIADIHCAAQhwIQFDI CCAAyAggAMgIIADICCAAyAggAOgcIABBHELADOgcIABCwAxBDOgQIABBDOgUIAB DLAUoECEEYAFDsGliTH2D3J2gBcAJ4AIABc4gBlQSSAQMwLjWYAQCgAQGqAQdnd 3Mtd2l6yAEKwAEB&sclient=gws-wiz 

 

argument vs parameter - Google 검색

2018. 5. 5. · Parameter는 함수 혹은 메서드 정의에서 나열되는 변수 명입니다. 반면 Argument는 함수 혹은 메서드를 호출할 때, 전달 혹은 입력되는 실제 값입니다.

www.google.com

 

반응형

댓글()