Node JS Tutorial in Hindi #56 Make PUT & DELETE REST API with Mongoose
Make Put and Delete API with Mongoose
Points of video:
- Make Put and Delete route
- Make Put and Delete request
- Write code for update and delete operation
- Test API
- Interview Questions
- Notes, Code and Playlist
Index.js file code
import mongoose from 'mongoose'
import express from 'express'
import studentModel from './model/studentModel.js';
const app = express();
app.use(express.json());
await mongoose.connect("mongodb://localhost:27017/school").then(()=>{
console.log("_______connected______");
})
app.get("/",async (req,resp)=>{
const studentData= await studentModel
resp.send(studentData)
})
app.post("/save",async (req,resp)=>{
console.log(req.body);
const {name,age,email}= req.body;
if(!req.body || !name || !age || !email){
resp.send({
message:"data not stored",
success:false,
storedInfo:null
})
return false
}
const studentData = await studentModel.create(req.body)
resp.send({
message:"data stored",
success:true,
storedInfo:studentData
})
})
app.put("/update/:id",async (req,resp)=>{
const id =req.params.id;
console.log(req.body,id);
const studentData= await studentModel.findByIdAndUpdate(id,{
...req.body
})
resp.send({
message:'data updated',
success:true,
info:studentData
})
})
app.delete("/delete/:id",async (req,resp)=>{
const id =req.params.id;
const studentData= await studentModel.findByIdAndDelete(id)
resp.send({
message:'data delete',
success:true,
info:studentData
})
})
app.listen(3200)
// async function dbConnection(){
// await mongoose.connect("mongodb://localhost:27017/school");
// const schema= mongoose.Schema({
// name:String,
// email:String,
// age:Number,
// })
// const studentsModel = mongoose.model('students',schema);
// const result = await studentsModel.find();
// console.log(result);
// }
// dbConnection();
schema/studentSchema.js file code
import mongoose from "mongoose";
const studentSchema= mongoose.Schema({
name:String,
age:Number,
email:String
})
export default studentSchema;
github Link
https://github.com/anil-sidhu/node-express-mongodb/tree/put-delete-api