return의 중요성

Jean·2023년 6월 15일
0

중복되는 부분이 많아서 checkDataAndReturn404 란 함수로 따로 빼서 적용이 잘되는지 확인하던중
안되는 코드를 발견..
checkDataAndReturn404 를 지나치고 바로 밑의 Comment.create 를 실행해서 자꾸
E11000 duplicate key error collection: spa_mall.comments index: 오류가 났다
저 오류는 유니크한 키값이 중복되면 나오는 오류이다..

const checkDataAndReturn404 = (data, res, msg, bool) => {
  if ((bool && data) || (!bool && !data)) {
    return res.status(404).json({ success: false, msg });
  }
};

router.post("/comment", async (req, res) => {
  ...
  const commentIdFind = await Comment.find({ commentId });
  //리팩토링 코드
  checkDataAndReturn404(
    commentIdFind.length,
    res,
    "해당 댓글아이디는 이미 존재합니다.",
    true
  );
  // 원래 코드
  // if (commentIdFind.length)
  //   return res
  //     .status(400)
  //     .json({ success: false, msg: "해당 댓글아이디는 이미 존재합니다" });

  await Comment.create({
    postId,
    content,
    commentId,
  });

return res.status(200).json({ success: true, msg: "댓글이 등록되었습니다." });
});

결국 잘 모르겠어서 튜터님께 갔다

 const a = checkDataAndReturn404(
    commentIdFind.length,
    res,
    "해당 댓글아이디는 이미 존재합니다.",
    true
  );
console.log(a)

console.log로 checkDataAndReturn404 로 찍어본 결과
엄청나게 긴 res 데이터가 나왔다...
그렇다 return이 안 되었던 것이다...

함수의 마지막 줄에서는 res가 마지막줄이라 상관이 없었지만 나머지 부분은 그렇지 않아서 오류가 생긴 것이였다

통수

놀라운 사실~!!
return을 넣으니 밑의 코드가 안돌아간다.... 아무래도 함수 안에 리턴이...쌩으로 있으면 그럴 수 밖에;;;
결국 리팩토링을 포기하고 원래 코드로 돌아갔다.....

router.post("/comment", async (req, res) => {
  ...
const commentIdFind = await Comment.find({ commentId });
if (commentIdFind.length)
   return res
     .status(400)
       .json({ success: false, msg: "해당 댓글아이디는 이미 존재합니다" });

  await Comment.create({
    postId,
    content,
    commentId,
  });

return res.status(200).json({ success: true, msg: "댓글이 등록되었습니다." });
});
profile
햇내기 개발자 지망생

0개의 댓글