배씨의 개발일지

CRUD구현,Mongoose이용 DB연결 본문

웹 개발

CRUD구현,Mongoose이용 DB연결

용찬 2023. 6. 15. 21:17

이 게시글은 아직 완성되지 않은 게시글입니다.

 

나만의 블로그 만들기를 통한 CRUD구현

 

 

게시판 작성하기 = C

추가적으로 해야하는 것

  • 변수명 변경
  • DB에서 데이터 생성 확인
router.post("/posts", async (req, res) => {
  const { postsId } = req.params;
  const { nickname, title, bodyText } = req.body;
  const date = date();

  const existsPosts = await Cart.find({ postsId: Number(postsId) });
  if (existsPosts.length) {
    return res.status(400).json({
      success: false,
      errorMessage: "이미 존재하는 게시물입니다.",
    });
  }

 

게시판 조회 = R

추가적으로 해야하는 것

  • 변수명 변경
  • DB에서 데이터 제대로 읽어오는지 확인
router.get("/posts", (req, res) => {
  res.status(200).json({ posts: posts });
});

 

게시판 상세 조회 = R

추가적으로 해야하는 것

  • 변수명 변경
  • DB에서 데이터 제대로 읽어오는지 확인
router.get("/posts/:postsId", (req, res) => {
  const { postsId } = req.params;
  const [detail] = posts.filter((posts) => posts.PostsId === String(postsId));
  res.json({ detail });
});

 

게시판 수정 = U

추가적으로 해야하는 것

  • 변수명 변경
  • DB에서 데이터 제대로 생성되는지 확인
router.put("/posts", async (req, res) => {
  const { postsId } = req.params;
  const { quantity } = req.body;

  const existsPosts = await Post.find({ postsId });
  if (existsPosts.length) {
    await Cart.updateOne(
      { postsId: postsId },
      { $set: { quantity: quantity } }
    );
  }
  res.status(200).json({ success: true });
});

 

게시판 삭제 = D

추가적으로 해야하는 것

  • 변수명 변경
  • DB에서 데이터 제대로 삭제되는지 확인
router.delete("/posts/:postsId", async (req, res) => {
  const { postsId } = req.params;

  const existsPosts = await Cart.find({ postsId });
  if (existsPosts.length) {
    await Post.deleteOne({ postsId });
  }
  res.json({ result: "success" });
});

 

 

 

 

 

Mongoose사용해서 DB연결하기.

 

const mongoose = require("mongoose");

const connect = () => {
  mongoose
    .connect("mongodb://127.0.0.1:27017/SOLO_BLOG")
    .then(() => {
      console.log("몽고디비 연결 성공");
    })
    .catch((err) => console.log(err));
};

mongoose.connection.on("error", (err) => {
  console.error("몽고디비 연결 에러", err);
});

module.exports = connect;

.then이용 DB연결 시 console.log

console.log로 DB연결만 확인

'웹 개발' 카테고리의 다른 글

NoSQL VS RDBMS  (0) 2023.08.16
VS CODE - mysql Sequelize  (0) 2023.07.12
나만의 뉴스피드 만들기  (3) 2023.07.11
나만의 블로그 만들기  (0) 2023.07.11
node.js 프로젝트 해야될 것들 DB저장까지  (0) 2023.06.29
Comments