본문 바로가기

개인과제(게시판,댓글CRUD구현)

[내일배움캠프] 개인 과제 게시판/댓글 CRUD기능 구현하기-댓글C/R-

//댓글 형성//
router.post("/posts/:id/comments", async (req, res) => {
    postId = req.params.id;
    //게시판의 id가 유효한 id인지 확인//
    const chkId = Post.find({ _id: Object(postId) })
    if (chkId) { console.log("게시판 특정 완료.") } else { return res.status(400).json({ message: "데이터형식을 확인해주세요" }) }
    //body에서 데이터 받음//
    const { content, user, password } = req.body;
    //작성 시간 설정//
    const day = new Date();
    //중복 아이디 확인 있다면 else로 없다면 if 구문//
    const existsUser = await Comment.find({ user });
    if (existsUser.length === 0) {
        //데이터를 작성했는지 확인//
        if (user) {
            //데이터를 작성했는지 확인//
            if (content) {
                //데이터를 작성했는지 확인//
                if (password) {
                    //데이터를 작성했는지 확인//
                    await Comment.create({ content, user, password, day, postId });
                    res.json({ message: "댓글을 생성하였습니다." })
                } else { return res.status(400).json({ message: "데이터형식을 확인해주세요" }) }
            } else { return res.status(400).json({ message: "데이터형식을 확인해주세요" }) }
        } else { return res.status(400).json({ message: "데이터형식을 확인해주세요" }) }
    } else { return res.status(400).json({ message: "이미 존재하는 user입니다." }) }
}
);

routes/comments.js의 댓글 생성 코드다.

게시글의 생성과정과 매우 흡사한 코드로 작성했다.

댓글은 각 게시글에 속해있다고 생각하기 때문에 댓글의 조회는 게시글의 id에 영향을 받도록 설정했다.

"/posts/:id/comments" 댓글작성할때의 url이다.

댓글을 작성할때 :id가 유효한지 확인한다.

postId = req.params.id;//url의 id 파라미터를 가져온다.

 const chkId = Post.find({ _id: Object(postId) })//가져온 id를 가지고 있는 데이터를 조회한다.
 if (chkId) { console.log("게시판 특정 완료.") }//id가 유효한 id라면 댓글 작성기능 코드로 갈 수 있다.

 

//db의 댓글 목록 불러오기//
router.get("/posts/:id/comments", async (req, res) => {
    postId = req.params.id
    //게시판 아이디가 일치하는지 확인//
    const comments = await Comment.find({ postId })
    //일치한다면 if구문 일치하지 않는다면 else//
    if (comments.length) {
        const commentList = comments.map((comment) => {
            //db의 오브젝트 아이디를 문자열로 변환//
            commentId = String(comment._id)
            return {
                "commentId": commentId,
                "user": comment.user,
                "content": comment.content,
                "day": comment.day,
            }
        })
        res.send({ commentList })
    } else { return res.status(400).json({ message: "데이터 형식을 확인해주세요" }) }
});

routes/comments.js의 댓글 조회 코드다.

게시글의 조회 과정과 매우 흡사한 코드로 작성했다.

const comments = await Comment.find({ postId }) //url의 id파라미터를 가지고 있는  comment 데이터를 db에서 조회한다.

일치하는 데이터를 가지고있는 댓글만 조회한다.