[TIL] Node.js 개인과제 (1) 23.06.14

이상훈·2023년 6월 15일
0

[내일배움캠프]

목록 보기
26/68

✔️오늘 한일!

  • Node.js 입문 강의 수강
  • 개인과제 - 게시판만들기

발생한 문제1

// 게시글 상세 조회
router.get("/posts/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;

  const result = await Posts.findById({ postId });

  if (!result) {
    return res.status(404).json({ message: "해당 ID로 작성된 게시글이 없습니다." });
  }

  res.status(200).json({
    Detail: {
      postId: result._id,
      user: result.user,
      title: result.title,
      content: result.content,
      createdAt: result.createdAt,
    },
  });
});

postId에 맞는 게시글 상세 조회를 구현하던 중 문제가 발생했다.
콘솔로 찍어보니 postId가 params로 넘어오긴 하는데 타입이 String으로 넘어오는데 몽구스에서 find를 해보면 값이 undefined나 null로 나와서 하나하나 다 콘솔로 찍어보기 시작했다.

콘솔도 찍어보고 구글링도 해보니 몽구스에서 find를 했을때 DB에 있는 id값이 ObjectId로 넘어와서 params에서 넘어오는 postId는 string이라 비교가 안되는거였다.

해결방법

const { ObjectId } = require("mongoose").Types;

// 게시글 상세 조회
router.get("/posts/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;

  const result = await Posts.findById({ _id: new ObjectId(postId) });

  if (!result) {
    return res.status(404).json({ message: "해당 ID로 작성된 게시글이 없습니다." });
  }

  res.status(200).json({
    Detail: {
      postId: result._id,
      user: result.user,
      title: result.title,
      content: result.content,
      createdAt: result.createdAt,
    },
  });
});

postId를 new ObjectId로 감싸서 비교해보니 정상적으로 결과값이 result에 들어갔다.

구글링하다보니 schema.virtual을 쓰는 방법도 있다고 하는데, 시간이 없어서 어떤 원리인지는 파악을 못했다.

각 router마다 오류가 발생했을 시 서버가 꺼지지 않도록 try / catch 구문을 작성했는데 이것을 함수화해서 코드를 좀 간소화시키는 방법을 찾아보려고 한다.

profile
코린이

0개의 댓글