skip to Main Content

I’m using node and mongoose to build my first API Restful but I’m having some problems with the "Delete" method.

async function remove(req, res) {
    const { id } = req.params
  
    const remove = await ProductsModel.deleteOne({ _id: id })
    
    const message = remove.ok ? 'success' : 'error'
  
    res.send({
      message,
    })
  }


module.exports = {
    remove
}

The route is correct

router.delete('/products/:id', ProductController.remove)

Postman response is always errors, I’ve tried different ID’s, but wont work.

I’ve tried different ID’s, and searching for the deleteOne method guide, but couldn’t find the error

2

Answers


  1. Chosen as BEST ANSWER

    I was looking at my code and discover that it was deleting, but the "if" was the problem.


  2. If the ID of the document you are trying to delete exists but still isn’t found or deleted, something else to try is casting the ID string to an ObjectId:

    const mongoose = require('mongoose');    
    const objectId = new mongoose.Types.ObjectId(id);
    const remove = await ProductsModel.deleteOne({ _id: objectId })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search