skip to Main Content

I am trying to delete a collection from mongodb using postmap API. Below is my code.The update function is working fine.But, delete function isn’t working. It’s displaying internal server error.I dont know why?

const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//uodate
router.put("/:id", async (req, res) => {
    if ((req.body.userId === req.params.id) || req.body.isAdmin) {
        if (req.body.password) {
            try {
                const salt = await bcrypt.genSalt(10);
                req.body.password = await bcrypt.hash(req.body.password, salt);
            }
            catch (err) {
                return res.status(500).json(err);
            }
        }
        try {
            const user = await User.findByIdAndUpdate(req.params.id, {
                $set: req.body,
            });
           return res.status(200).json("Account has been updated");
        }
        catch (err) {
            return res.status(500).json(err);
        }
    }
    else return req.status(400).json("You can only update your account!!!");
});
//delete
router.delete("/:id", async (req, res) => {
    if ((req.body.userId === req.params.id) || req.body.isAdmin) {
        try {
           await User.deleteOne(req.params.id);
            return res.status(200).json("Account has been deleted");
        }
        catch (err) {
            return res.status(500).json(err);
        }
    }
    else return res.status(400).json("You can only update your account!!!");
});



module.exports = router;

Help me with thispostman API screenshot.

3

Answers


  1. You are using deleteOne() method. If you want to delete whole collection, you should use deleteMany() method:

    await User.deleteMany({});
    
    Login or Signup to reply.
  2. The Model.deleteOne method expects a filter object, like {name: "value'"}. You are passing req.params.id which is a string. If you dig out the full text of the error, it will likely complain about that string not being an object.

    You probably meant to use the Model.findByIdAndDelete method like

    await User.findByIdAndDelete(req.params.id);
    
    Login or Signup to reply.
  3. Try this:

    await User.deleteOne({_id:req.params.id});
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search