skip to Main Content

This is constantly giving me error that Contact.remove() is not a function. I want to delete a particular contact by passing an id.

const DeleteContact = asyncHandler(async (req, res) => {

    const contact = await Contact.findById(req.params.id);
    if (!contact) {
       res.status(404)
       throw new Error("Contact not found");
    }
  
 
    await Contact.remove();
    res.status(200).json(contact);
});


2

Answers


  1. I would do something like this:

    const DeleteContact = asyncHandler(async (req, res) => {
      const contact = await Contact.findOneAndDelete({ _id: req.params.id });
      if (!contact) {
        res.status(404);
        throw new Error("Contact not found");
      }
    
      res.status(200).json(contact);
    });
    

    Your error is probably because of using delete instead of deleteOne, i think they recently had a change on their function names

    Login or Signup to reply.
  2. You should use Model.findByIdAndDelete() if you know the _id of the document to would like to delete like so:

    const DeleteContact = asyncHandler(async (req, res) => {
       try{
          const contact = await Contact.findByIdAndDelete(req.params.id);
          if (!contact) {
             return res.status(400).json({
                message: 'Unable to delete. Contact not found.'
             })
          }
          res.status(200).json(contact);
       }catch(err){
          console.log(err);
          return res.status(500).json({
             message: 'Error on server.'
          })
       }
    });
    

    Note: the try/catch may be unnecessary if your asyncHandler is well written but I did not want to assume.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search