본문 바로가기

JavaScript

Node.js 입문 주차 1주차_4

728x90

Node.js 입문 주차 1주차_4


MongoDB, Studio 3T 설치

 

📌 mongoose

DB Clinet 역할

npm install mongoose

MongoDB 연결

 

📄 app.js

const express = require('express');
const app = express();
const port = 3000;

const goodsRouter = require('./routes/goods.js');
const connect = require('./schemas/index.js');
connect();

app.use(express.json());

app.use("/api", goodsRouter);

app.listen(port, () => {
  console.log(port, '포트로 서버가 열렸어요!');
});

 

📄 /schemas/index.js

const mongoose = require("mongoose");

const connect = () => {
  mongoose
    .connect("mongodb://localhost:27017/spa_mall")
    .catch(err => console.log(err));
};

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

module.exports = connect;

📌 에러 발생!

(node:17028) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning. (Use `node --trace-deprecation ...` to show where the warning was created)

 

 

📌 connet 변경 & set 추가

const connect = () => {
  mongoose
    .set('strictQuery', true)
    .connect("mongodb://127.0.0.1:27017/spa_mall")
    .catch(err => console.log(err));
};

이렇게 설정하니 에러없이 서버 연결됨.

 


POST실습

 

📄 /schemas/goods.js

const mongoose = require("mongoose");

const goodsSchema = new mongoose.Schema({
  goodsId: {
    type: Number,
    required: true,
    unique: true
  },
  name: {
    type: String,
    required: true,
    unique: true
  },
  thumbnailUrl: {
    type: String,
  },
  category: {
    type: String,
  },
  price: {
    type: Number,
  }
});

module.exports = mongoose.model("Goods", goodsSchema);

 

📄 /schemas/index.js

const mongoose = require("mongoose");

const connect = () => {
  mongoose
    .set('strictQuery', true)
    .connect("mongodb://127.0.0.1:27017/spa_mall")
    .catch(err => console.log(err));
};

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

module.exports = connect;

 

📄 /routes/goods.js

  const Goods = require("../schemas/goods");
  router.post("/goods", async (req, res) => {
    const { goodsId, name, thumbnailUrl, category, price } = req.body;
  
    const goods = await Goods.find({ goodsId });
    if (goods.length) {
      return res.status(400).json({ success: false, errorMessage: "이미 있는 데이터입니다." });
    }
  
    const createdGoods = await Goods.create({ goodsId, name, thumbnailUrl, category, price });
  
    res.json({ goods: createdGoods });
  });

  module.exports = router;

 

📄 app.js

app.use(express.json());

// localhost:3000/api -> goodsRouter
app.use("/api", [goodsRouter]);

 

📄 POST할 입력된 JSON 형식 데이터

{
   "goodsId": 2,
   "name": "시원한 콜라",
   "thumbnailUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRk7JqMw7ZYZP4ZW136wcoMTmLzbrMIJzUWb1Dhu9cHwCPp0gA&usqp=CAc",
   "category": "drink",
   "price": 3000
}

POST 성공!

 

이미 있는 데이터입니다.

 

 

DB저장된 goods 확인


장바구니 구현

 

📄 /schemas/carts.js

const mongoose = require("mongoose");

const cartSchema = new mongoose.Schema({
  goodsId: {
    type: Number,
    required: true,
    unique: true
  },
  quantity: {
    type: Number,
    required: true,
  }
});

module.exports = mongoose.model("Cart", cartSchema);

 

📄 /routes/carts.js

const express = require("express");
const router = express.Router();
const Cart = require("../schemas/cart.js");
const Goods = require("../schemas/goods.js");

//localhost:3000/api/carts GET Method
router.get("/carts", async(req,res) => {
    const carts = await Cart.find({});

    //[{goodsId, quantity}] -> cart
    const goodsIds = carts.map((cart) => {
        return cart.goodsId;
    })
    // goodsIds = [2, 11, 19];

    const goods = await Goods.find({goodsId: goodsIds});
    // Goods에 해당하는 모든 정보를 가지고 올건데,
    // 만약 goodsIds 변수 안에 존재하는 값일 때에만 조회하라.

    const results = carts.map((cart) => {
        return {
            "quantity": cart.quantity,
            "goods": goods.find((item) => item.goodsId === cart.goodsId),

        }
    })

    res.json({
        "carts": results,
    })

});


module.exports = router;

 

 

📄 app.js

const cartsRouter = require("./routes/carts.js");

// localhost:3000/api -> goodsRouter, cartsRouter
app.use("/api", [goodsRouter, cartsRouter]);

 

carts 원하는 키:배열 형태로 보내기


📄 장바구니 상품 추가

  const Cart = require("../schemas/cart.js")
  router.post("/goods/:goodsId/cart", async(req,res) => {
    const {goodsId} = req.params;
    const {quantity} = req.body;

    const existCarts = await Cart.find({goodsId});
    if (existCarts.length){
      return res.status(400).json({
        success:false,
        errorMessage:"이미 장바구니에 해당하는 상품이 존재합니다."
      })
    }

    await Cart.create({goodsId, quantity});

    res.json({result: "success"})
  })

 

 

📄 장바구니 수정

  router.put("/goods/:goodsId/cart", async(req,res) => {
    const {goodsId} = req.params;
    const {quantity} = req.body;

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

 

 

📄 장바구니 삭제

  router.delete("/goods/:goodsId/cart", async(req,res) => {
    const {goodsId} = req.params;

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

  })

'JavaScript' 카테고리의 다른 글

Node.js 입문 1주차, 개인과제  (0) 2022.12.16
Node.js 입문 주차 1주차_5  (0) 2022.12.14
Node.js 입문 주차 1주차_3  (0) 2022.12.13
Node.js 입문 주차 1주차_2  (0) 2022.12.13
Node.js 입문 주차 1주차  (0) 2022.12.12