코드에서 MongoDB 이용

김정현·2023년 1월 17일
0
post-thumbnail

mongoose 설치

npm i mongoose

mongoose의 모델이란?

  • 데이터베이스에 데이터를 저장해줄때 데이터의 구조를 담당한다.

mongoose에서는 모델이 왜 필요한가?

  • mongoose에서 데이터를 모델링할시 Schema라는 객체를 사용하는데 이 Schema를 이용해 document를 생성할 때 모델이 사용된다.

웹 서버에서 MongoDB에 연결
-index.js

const mongoose = require("mongoose");
const connect = () => { mongoose.connect("mongodb://localhost:27017/spa_mall").catch((err) => {
    console.error(err);
  });
};
mongoose.set('strictQuery',true)
module.exports = connect;
  • app.js
const connect = require("./schemas");
connect();
  • 모델 작성
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);
  • body로 전달 받은 JSON 데이터를 바로 사용할 수 없다
app.use(express.json());
  • post 작성
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 createdGodds = await Goods.create({ goodsId, name, thumbnailUrl, category, price })
  res.json({goods: createdGodds})
})

0개의 댓글