Get, Post, Delete and Update Database with help of Postman and using mongoDB

 const express=require('express');

const router=express.Router();
const {Categories} =require('../models/categories')

router.get(`/`, async (req,res)=>{
 
    const categoriesList=await Categories.find();

    res.status(200).send(categoriesList);

    if(!categoriesList){
        res.status(500).json({success: false})
    }
})


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

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

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


router.post('/',async (req, res)=>{
    let category=new Categories({
        name:req.body.name,
        icon:req.body.icon,
        color:req.body.color,
    })

    category=await category.save();

    if(!category)
    return res.status(404).send('the category cannot be created!');

    res.send(category);
})


router.put('/:id', async(req, res)=>{
    const Category=await Categories.findByIdAndUpdate(
        req.params.id,
        {
            name: req.body.name,
            icon: req.body.icon,
            color: req.body.color,
        }
    )
    if(!Category)
    return res.status(404).send('the category cannot be created!');

    res.send(Category);
})

// router.put(':/id', async(req, res)=>{
//     const category=await Categories.findByIdAndUpdate(
//         req.params.id,{
//             name: req.body.name,
//             icon: req.body.icon,
//             color: req.body.color,
//         },{
//             new:true
//         }
//     )
//     if(!category)
//     return res.status(400).send('the category cannot be created!');
//     res.send(category);
// })

router.delete('/:id', async (req, res) => {
   
    try {

      const category = await Categories.findByIdAndRemove(req.params.id);
      if (category) {
        return res.status(200).json({ success: true, message: 'The category is deleted now' });
      } else {
        return res.status(404).json({ success: false, message: 'Category not found' });
      }
    } catch (err) {
      return res.status(404).json({ success: false, error: err });
    }
  });


 
 
 
  module.exports = router;
 

Post a Comment

0 Comments