Question:
How to delete documents from a mongoDB collection without an error?

Problem:

I have an inventory management system app that uses React for the front end, express for the backend, and 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:tech@nodeproject.azbwi6o.mongodb.net/?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


Solution:

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 });

  }

});


Suggested blogs:

>Use of Singletons in .NET Core in AWS Lambda

>How to do PHP Decryption from Node.js Encryption

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to Set up the local environment for Angular development?

>How to solve encoding issue when writing to a text file, with Python?

>Create a function that convert a dynamic Json to a formula in Typescript

>Narrow SomeType vs SomeType[]

>Use Firebase Realtime Database with ASP.NET MVC App

>How to Set up the Android emulator?

>Step by Step guide to Deploy Terraform in Azure using GitHub Actions

>Testing react components using Hooks and Mocks


Ritu Singh

Ritu Singh

Submit
0 Answers