혼자 고민해보기_ 개발/TIL (Today I Learned)

20230707(금)_ 노드 JS 심화 Lv4 과제 보완

nuri-story 2023. 7. 7. 22:42

금일 달성 항목

1)  노드 JS 심화 Lv4 과제 완료

2) 후발대 수업 참여 (객체지향)


문제 해결 과정 1- npx sequelize db:creat 실행 오류

[문제]

각각의 게시글에 좋아요가 얼마나 카운팅 되어있는지 확인하는 코드를 작성해야하는 상황이었습니다.

 

[시도 및 해결]

like를 연결하는데 성공하였으나 게시글의 각각의 사용자들이 좋아요한 카운트 수는 노출되지 않았습니다.

router.get("/posts", async (req, res) => {
  try {
    const posts = await Posts.findAll({
      attributes: [
        "postId",
        "userId",
        "title",
        "createdAt",
        "updatedAt",
        [Sequelize.fn("COUNT", Sequelize.col("Likes.LikeId")), "likeCount"],
      ],
      include: [
        {
          model: Likes,
          attributes: [],
        },
      ],
      order: [["createdAt", "DESC"]],
      group: ["Posts.postId"], // 게시물 ID로 그룹화하여 좋아요 개수를 가져옵니다.
    });

    return res.status(200).json({ data: posts });
  } catch (error) {
    console.error("오류가 발생했습니다.", error);
    res.status(500).json({ message: "오류가 발생했습니다." });
  }
"data": [
    {
      "postId": 2,
      "userId": 1,
      "title": "안녕하세요 게시글2 제목입니다.",
      "createdAt": "2023-07-06T09:28:42.000Z",
      "updatedAt": "2023-07-06T09:28:42.000Z",
      "likeCount": 0
    },
    {
      "postId": 1,
      "userId": 1,
      "title": "수정된 게시글 제목입니다.",
      "createdAt": "2023-07-06T09:28:17.000Z",
      "updatedAt": "2023-07-06T09:33:45.000Z",
      "likeCount": 0
    }
  ]
}

[알게된 점]

좀 더 고민해봐야합니다..