How to create Get, Post, Put and Delete in using MongoDB

 main file is app.js


const express=require('express');
const mongoose=require('mongoose');
const cors=require('cors');
const morgan=require('morgan');
const bodyParser=require('body-parser');


const app=express();
app.use(cors());
app.options('*',cors);


app.use(morgan('tiny'));

const details=require('./router/details');

require('dotenv/config');

const api=process.env.API_URL;

app.use(bodyParser.json());


app.use(`${api}/details`,details);

mongoose.connect(process.env.CONNECTION_STRING,{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    dbName:'eshop-database'
})

.then(()=>{
    console.log("The database Connection is ready now ....");
})

.catch((err)=>{

    console.log(err);
})


app.listen(3000,() =>{
    console.log("The Sever is  running http://localhost:3000");
})



router file which is store details.js 


const express = require('express');
const router = express.Router();
const { details } = require('../model/details'); // Assuming the model is exported as 'details'

// GET route to retrieve all details
router.get('/', async (req, res) => {
  try {
    const detailsList = await details.find();
    res.status(200).json(detailsList);
  } catch (error) {
    res.status(500).json({ success: false, message: 'An error occurred while retrieving details.' });
  }
});


router.get('/:id', async(req, res)=>{
  const detail =await details.findById(req.params.id);

  if(!detail){
      res.status(500).json({message: 'the category with the given ID was'})
  }

  res.status(200).send(detail);
})

// POST route to create a new details entry
router.post('/', async (req, res) => {
  try {
    const { name, email, mobile, message } = req.body;
   
    const newDetails = new details({
      name,
      email,
      mobile,
      message,
    });
   
    const savedDetails = await newDetails.save();
   
    if (!savedDetails) {
      return res.status(404).json({ success: false, message: 'The details entry could not be created.' });
    }
   
    res.status(201).json(savedDetails);
  } catch (error) {
    res.status(500).json({ success: false, message: 'An error occurred while saving the details.' });
  }
});
router.put('/:id', async (req, res) => {
  try {
    const updatedDetails = await details.findByIdAndUpdate(
      req.params.id,
      {
        name: req.body.name,
        email: req.body.email,
        mobile: req.body.mobile,
        message: req.body.message,
      },
      { new: true } // Option to return the updated document
    );

    if (!updatedDetails)
      return res.status(404).send('The details cannot be updated.');

    res.send(updatedDetails);
  } catch (error) {
    res.status(500).send('An error occurred while updating the details.');
  }
});



router.delete('/:id', async(req, res) =>{
  try{
    const detail=await details.findByIdAndRemove(req.params.id)

    if(detail){
      return res.status(200).json({success :true, message:"The Details is deleted now "});
    }
    else{
      return res.status(404).json({success:false, message:'the deatils is not found'});
    }
  } catch(err){
    return res.status(404).json({success:false, error:err});
  }
})

module.exports = router;



model file while is store details.js


const mongoose = require('mongoose');

const detailsSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
    },
    mobile: {
        type: Number,
    },
    message: {
        type: String,
    }
});

exports.details = mongoose.model('Details', detailsSchema);







Post a Comment

0 Comments