• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 댓글 수 구현 질문

댓글 수 구현 질문

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #36154

    케이크
    참가자

    안녕하세요. 프로젝트 진행중 댓글수를 구현해보기 위해 이것저것 해보는중입니다. 지금 생각한 방법은 post에 commentAll이라는 값을 default 로 0으로 준 뒤, 코멘트를 작성하고 삭제한 뒤에 해당 post의 postId값을 가진 comment들을 전부 불러와서 그 배열의 length를 updateone을 이용해 넣어주는 방식입니다. 다만 아직 front가 만들어지지 않은 상황이라 테스트가 잘 안돼서 게시판에 질문 남겨봅니다 감사합니다. 아래는 코드입니다.

    // 코멘트 작성: 유저확인

    router.post('/detail/:postId', authMiddlewares, async (req, res) => {
      let counter = await CommentCounter.findOne({ name: 'totalComment' }).exec();
      counter.totalComment++;
      counter.save();
      const { userId } = res.locals.user;
      const existingUser = await User.findOne({ _id: userId });
      const commentId = counter.totalComment;
      const { comment } = req.body;
      const commentDate = new Date().toLocaleDateString();
      const userNickname = existingUser.userNickname;
      const userProfileImage = existingUser.userProfileImage;
      const authorId = existingUser._id;
      const postId = parseInt(req.params);

      if (!comment) {
        res.status(400).json({ success: false, message: '내용을 입력하세요' });
      }
      const createdComment = await Comment.create({
        commentId,
        comment,
        commentDate,
        userNickname,
        userProfileImage,
        authorId,
        postId,
      });
      const commentAll = await Comment.find({ postId: parseInt(postId) });
      await Post.updateOne(
        { postId: parseInt(postId) },
        { $set: { commentAll: commentAll.length } }
      );
      res.status(200).json({
        success: true,
        message: '댓글 저장 성공',
        comment: createdComment,
      });
    });

    // 코멘트 삭제: 유저확인
    router.delete('/comment/:commentId', authMiddlewares, async (req, res) => {
      const { commentId } = req.params;
      const { userId } = res.locals.user;
      const existingComment = await Comment.find({
        commentId: parseInt(commentId),
      });

      if (userId !== existingComment.authorId) {
        res
          .status(400)
          .json({ success: false, message: '내가 쓴 댓글이 아닙니다' });
      } else {
        await Comment.deleteOne({ commentId: parseInt(commentId) });
        const commentAll = await Comment.find({
          postId: parseInt(existingComment.postId),
        });
        await Post.updateOne(
          { postId: parseInt(existingComment.postId) },
          { $set: { commentAll: commentAll.length } }
        );
        res.status(200).json({ success: true, message: '댓글 삭제 성공' });
      }
    });

     

    #36165

    codingapple
    키 마스터

    그럼 글 하나에 댓글이 10만개면

    글 로드할 때 마다 댓글도 10만개 전부 가져와야해서 비효율적이라

    댓글총 갯수를 어디 저장해두고 댓글발행할 때 마다 +1 하거나

    .count()같은거 써서 document 갯수만 세라고 하거나 하면 됩니다 

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠