Thunder client가 API 동작들을 테스트할 수 있는 편리한 툴인 것처럼 Studio 3T는 database 관련 동작들을 테스트할 수 있는 툴이다.
데이터의 조회, 삽입, 삭제 등이 가능하다.
Node.js에서 MongoDB 데이터베이스에 연결하기 위해 설치해야하는 라이브러리.
npm install mongoose
Collections에 들어가는 문서에 어떤 종류의 값이 들어가는지 정의한다.
null, String, Number, Date, Buffer, Boolean, ObjectId, Array
데이터베이스의 구조.
프로젝트 구조:
// 1
const mongoose = require("mongoose");
// 2
const connect = () => {
mongoose
.connect("mongodb://localhost:27017/spa_mall")
.catch((err) => console.log(err));
};
// 3
mongoose.connection.on("error", (err) => {
console.error("몽고디비 연결 에러", err);
});
// 4
module.exports = connect;
const mongoose = require("mongoose");
// 1
const goodsSchema = new mongoose.Schema({
// 2
goodsId: {
// 3
type: Number,
required: true,
unique: true,
},
name: {
type: String,
required: true,
unique: true,
},
thumbnailUrl: {
type: String,
},
category: {
type: String,
},
price: {
type: Number,
},
});
// 4
module.exports = mongoose.model("Goods", goodsSchema);
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);
const express = require("express");
const router = express.Router();
// 1
const Goods = require("../schemas/goods");
// 2 // 7
// goods 추가 API
router.post("/goods", async (req, res) => {
// 3
const { goodsId, name, thumbnailUrl, category, price } = req.body;
// 4
const goods = await Goods.find({ goodsId });
// 5
if (goods.length) {
return res.status(400).json({ success: false, errorMessage: "이미 있는 데이터입니다." });
}
// 6
const createdGoods = await Goods.create({ goodsId, name, thumbnailUrl, category, price, });
res.json({ goods: createdGoods });
});
// 장바구니 상품 추가 API
// 1
const Cart = require("../schemas/cart.js");
// 2
router.post("/goods/:goodsId/cart", async (req, res) => {
// 3
const { goodsId } = req.params;
const { quantity } = req.body;
// 4
const existsInCart = await Cart.find({ goodsId });
if (existsInCart.length) {
return res.status(400).json({
success: false,
message: "카트에 상품이 존재합니다.",
});
}
// 5
await Cart.create({ goodsId, quantity });
res.json({ result: "success" });
});
// 장바구니 상품 수량 수정 API
// 1
router.put("/goods/:goodsId/cart", async (req, res) => {
// 2
const { goodsId } = req.params;
const { quantity } = req.body;
// 3
const existsInCart = await Cart.find({ goodsId });
if (existsInCart.length) {
await Cart.updateOne(
{ goodsId: goodsId },
{ $set: { quantity: quantity } }
);
}
res.status(200).json({ success: true });
});
// 장바구니 상품 삭제 API
// 1
router.delete("/goods/:goodsId/cart", async (req, res) => {
// 2
const { goodsId } = req.params;
// 3
const existsInCart = await Cart.find({ goodsId });
if (existsInCart.length) {
await Cart.deleteOne({ goodsId });
}
res.status(200).json({ success: true });
});
module.exports = router;
Cart.updateOne(
// 1
{ goodsId: goodsId },
// 2
{ $set: { quantity: quantity }
}(1) Cart에서 goodsId가 goodsId인 데이터를 찾아서const express = require("express");
const router = express.Router();
// 1
const Cart = require("../schemas/cart");
const Goods = require("../schemas/goods");
// 2
// 장바구니 조회 API
router.get("/carts", async (req, res) => {
// 3
const carts = await Cart.find({});
// 4
const goodsIds = carts.map((cart) => {
return cart.goodsId;
});
// 5
const goods = await Goods.find({ goodsId: goodsIds });
// 6
const results = carts.map((cart) => {
return {
quantity: cart.quantity,
goods: goods.find((item) => item.goodsId === cart.goodsId),
};
});
// 7
res.json({
carts: results,
});
});
module.exports = router;
const express = require("express");
const app = express();
const port = 3000;
const goodsRouter = require("./routes/goods.js");
// 1
const connect = require("./schemas");
// 2
connect();
// 3
app.use(express.json());
app.use("/api", [goodsRouter]);
app.listen(port, () => {
console.log(port, "포트로 서버가 열렸어요!");
});