mongoose란?
node.js에서 mongodb를 편리하게 사용할 수 있도록 제공하는 라이브러리
mongoose 사용법
mongoose의 문서(document)란?
mongoose의 컬렉션이란?
mongoose의 스키마란?
대표적인 스키마의 타입
1. schemas 폴더에서 객체로 스키마 모델을 생성하여 exports를 해준다.
const goodsSchema = new mongoose.Schema({
goodsId: {
type: Number,
required: true,
unique: true,
},
name: {
type: String, // 이름은 문자
required: true, // 이름이 없는 물건은 존재하지 않아 , 무조건 있어야 한다.
unique: true, // 중복 허용하지 않아.
},
thumnailUrl: {
type: String,
},
category: {
type: String,
},
price: {
type: Number,
},
});
module.exports = mongoose.model("Goods", goodsSchema);
// Goods가 컬렉션 이름
2. routes 폴더에서 스키마를 상수로 불러온다.
post(추가)를 하여 req.body로 받아온 후에 뿌려준다
const Goods = require("../schemas/goods");
// 데이터베이스에 접근해야하기 때문에 async 동기적 처리
router.post("/goods", async (req, res) => {
const { goodsId, name, thumnailUrl, category, price } = req.body;
// goodsId는 unique 중복x
const goods = await Goods.find({ goodsId });
if (goods.length) {
// goods에 있다면
return res
.status(400)
.json({ success: false, errorMessage: "이미 존재하는 GoodsId입니다." });
}
// 데이터베이스에 접속되면 뿌려준다.
const createGoods = await Goods.create({
goodsId,
name,
thumnailUrl,
category,
price,
});
res.json({ goods: createGoods });
});