Trying to delete documents from a mongoDB collection getting an error

I have an inventory management system app that uses react for the frontend and express for the backend along with mongoDB. I have a table of products and next to each product there is a delete button. When I click the delete button I want to delete that product from my mongoDB database.

I set up an endpoint in express, and I am passing the correct id for each product, but I keep getting an 500 error. here is the frontend code where the delete button is handled:

import React, { Component } from 'react'

class ProductRow extends Component {
    constructor(props) {
        super(props)
        this.destroy = this.destroy.bind(this)
    }

    async destroy() {
        try {
          const productid = this.props.productid  
          const response = await fetch(`http://localhost:5000/product/delete/${productid}`, {
            method: 'DELETE'
          });
      
          if (!response.ok) {
            throw new Error('Failed to delete product');
          }
      
          // Remove the deleted product from the state
          const updatedProducts = this.state.products.filter(product => product.id !== productid);
          this.setState({ products: updatedProducts });
        } catch (error) {
          console.error('Error deleting product:', error);
        }
      }
    
    render () {
        
        return (
            <tr>
                <td>{this.props.product.name}</td>
                <td>{this.props.product.category}</td>
                <td>{this.props.product.price}</td>
                <td>{this.props.product.instock.toString()}</td>
                <td class="text-right"><button onClick={this.destroy} class="btn btn-info">Delete</button></td>
            </tr>
        )
    }
}

export default ProductRow

here is the express server code:

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
const cors = require("cors");


  app.use(bodyParser.json());
  app.use(cors());


var mongoose = require('mongoose')
var dbURL = 'mongodb+srv://mario:[email protected]/?retryWrites=true&w=majority'

try {
    mongoose.connect(dbURL) 
    console.log('Mongo connected')
}
catch(error) {
    console.log(error)

}

// Create a mongoose model
var Product = mongoose.model('Product', {
        "id": Number,
    "product": {
    "productid": Number,
    "category": String,
    "price": Number,
    "name": String,
    "instock": Boolean
    }

  });

  // Endpoint to fetch products
  app.get('/product/get/', async (req, res) => {
    try {
      // Fetch products from the database using Mongoose
      const products = await Product.find({});
      res.json(products); // Send products as a JSON response
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  });

// Endpoint to handle POST request for creating a product
app.post('/product/create', async (req, res) => {
    try {
      const {id, name, category, price } = req.body;

      const productData = {
        id: id,
        product: {
          productid: id,
          category: category,
          price: price,
          name: name,
          instock: true
        }
      };
      
      const newProduct = new Product(productData);
      const savedProduct = await newProduct.save();
      res.status(201).json(savedProduct);
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  });

  // Endpoint to delete a product by its ID
app.delete('/product/delete/:id', async (req, res) => {
  const productId = req.params.id;

  try {
    const documentToDelete = { _id: `ObjectID(${productId})` };
    const deletedProduct = await Product.deleteOne(documentToDelete);
  

    if (!deletedProduct) {
      return res.status(404).json({ message: 'Product not found' });
    }

    res.json({ message: 'Product deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

var server = app.listen(5000, () => {
    console.log('server is listening on port', server.address().port)
})

I believe the error is from this line: const deletedProduct = await Product.deleteOne(documentToDelete); this is the value of documentToDelete: { _id: 'ObjectID(657142d6ad5a5e69a000758d)' } Could I not be using the deleteOne method correctly?

I tried fixing it myself, by looking at other examples and the official MongoDB documentation

  • Show the error message

    – 

Try this code to resolve the error you are facing :

app.delete('/product/delete/:id', async (req, res) => {
  const productId = req.params.id;

  try {
    if (!mongoose.Types.ObjectId.isValid(productId)) {
      return res.status(400).json({ message: 'Invalid product id' });
    }

    const deletedProduct = await Product.deleteOne({ _id: productId });

    if (deletedProduct.deletedCount == 0) {
      return res.status(404).json({ message: 'Product not found' });
    }

    res.json({ message: 'Product deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

Leave a Comment