UPDATE AND DELETE handling PUT ? PATCH and DELETE request in REST API
UPDATE the student by its id
app.patch("/students/:id", async (req, res)=>{try{const _id = req.params.id;const updateStudent = await Student.findByIdAndUpdate(_id, req.body, {new:true} )res.send(updateStudent)}catch(e){res.status(404).send(updateStudent);console.log(e)}})
app.delete("/students/:id",async (req, res)=>{try{const _id = req.params.id;const deleteStudent = await Student.findByIdAndDelete(_id, req.body)res.send(deleteStudent)}catch(e){res.status(404).send(e);console.log(e)}})
const express = require("express");require("./db/conn");const Student = require("./models/students");const app = express();const port = process.env.PORT || 8000;// use express.jsonapp.use(express.json());// define rootapp.get("/",(req, res)=>{res.send("home page")})// create// app.post("/students",(req,res)=>{// console.log(req.body);// const user = new Student(req.body);// user.save().then(()=>{// res.status(201).send(user)// }).catch((e)=>{// res.status(400).send(e);// }),// async functionapp.post("/students", async(req, res)=>{try{const user = new Student(req.body);const result = await user.save();res.status(201).send(result)}catch{res.status(400).send(e);}})// read the data of registrered studentapp.get("/students", async (req, res)=>{try{const studentdata = await Student.find();res.send(studentdata);}catch(e){console.log(e);}})// get the individual student data using id//app.get("/students/:id", async (req, res)=>{try{const _id = req.params.id;// console.log(req.params.id);// res.send(req.params.id);const studentData = await Student.findById(_id);if(!studentData){return res.status(404).send();}else{res.send(studentData);}}catch(e){console.log(e);}})// UPDATE the student by its idapp.patch("/students/:id", async (req, res)=>{try{const _id = req.params.id;const updateStudent = await Student.findByIdAndUpdate(_id, req.body, {new:true} )res.send(updateStudent)}catch(e){res.status(404).send(updateStudent);console.log(e)}})// DELETE student by idapp.delete("/students/:id",async (req, res)=>{try{const _id = req.params.id;const deleteStudent = await Student.findByIdAndDelete(_id, req.body)res.send(deleteStudent)}catch(e){res.status(404).send(e);console.log(e)}})app.listen(port, ()=>{console.log(`connecting port ${port}`)});
Post a Comment