freePlans.js
router.post("/consumption", async (req, res) => {
try {
const { userId, planName, planStart, planEnd, description, pattern } =
req.body;
const newFreePlan = new Free({
planName,
planStart,
planEnd,
description,
pattern,
user: userId,
});
const savedPlan = await newFreePlan.save();
await User.updateOne(
{ _id: userId },
{ $push: { freePlans: savedPlan._id } }
);
res.status(201).json(savedPlan);
} catch (err) {
console.error(err);
res.status(500).json({ message: "Server error" });
}
});
MyPlan.js
const express = require("express");
const router = express.Router();
const Free = require("../models/Free");
const User = require("../models/User");
router.post("/consumption", async (req, res) => {
try {
const { userId, planName, planStart, planEnd, description, pattern } =
req.body;
const newFreePlan = new Free({
planName,
planStart,
planEnd,
description,
pattern,
user: userId,
});
const savedPlan = await newFreePlan.save();
await User.updateOne(
{ _id: userId },
{ $push: { freePlans: savedPlan._id } }
);
res.status(201).json(savedPlan);
} catch (err) {
console.error(err);
res.status(500).json({ message: "Server error" });
}
});
router.get("/consumption/find", async (req, res) => {
try {
const userId = req.query.userId;
const data = await Free.find({ user: userId }).sort({ createdAt: -1 });
res.json(data);
} catch (err) {
console.error(err);
res.status(500).send("Server error");
}
});
router.get("/consumption/find/:id", async (req, res) => {
try {
const planId = req.params.id;
const userId = req.query.userId;
const Freeplan = await Free.findOne({ _id: planId, user: userId });
console.log(Freeplan);
res.json(Freeplan);
} catch (err) {
console.error(err);
}
});
router.post(`/consumption/update/:id`, async (req, res) => {
try {
const planId = req.params.id;
const { planName, planStart, planEnd, description } = req.body;
const FreePlan = await Free.findByIdAndUpdate(
planId,
{ planName, planStart, planEnd, description },
{ new: true }
);
res.json(FreePlan);
console.log(FreePlan);
} catch (err) {
console.error(err);
}
});
router.post(`/consumption/delete/:id`, async (req, res) => {
try {
const planId = req.params.id;
const Freeplan = await Free.findByIdAndDelete(planId);
console.log("지운 내역: \n", Freeplan);
res.json(Freeplan);
} catch (err) {
console.error(err);
}
});
module.exports = router;