Warm tip: This article is reproduced from stackoverflow.com, please click
javascript mongodb mongoose node.js routes

How can I get this DELETE route to work in my products.js route?

发布于 2020-03-29 21:02:10

I'm having a problem getting my delete route working for removing a single product by grabbing it's _id (5e335c57bd37eb1dd4d99b1f) in Mongoose. I assumed that simply copying the update route and changing it around a bit would work. All the other routes work fine in Postman.

products.js

const express = require("express"),
router = express.Router(),
Product = require("../models/product.model");

// Product list route
router.get("/", function(req, res) {
    Product.find().then(products => {
        res.status(200).json(products);
    }).catch(err => {
        res.status(400).send(`Recieving products failed. Error details: ${err.message}`);
    });
})

// Product details route
router.get("/:product_id", function(req, res) {
    Product.findById(req.params.product_id).then(product => {
        res.status(200).json(product);
    }).catch(err => {
        res.status(400).send(`Recieving product details failed. Error details: ${err.message}`);
    });
})

// Product create logic route
router.post("/add", function(req, res) {
    let product = new Product(req.body);
    product.save().then(product => {
        res.status(200).json({"product": `Product added successfully. Created product details: ${product}`});
    }).catch(err => {
        res.status(400).send(`Adding new product failed. Error details: ${err.message}`);
    });
})

// Product update route
router.put("/:product_id", function(req, res) {
    Product.findById(req.params.product_id).then(product => {
        product.name = req.body.name;
        product.description = req.body.description;
        product.price = req.body.price;
        product.stock = req.body.stock;

        product.save().then(product => {
            res.status(200).json(`Product updated! Updated product details: ${product}`);
        }).catch(err => {
            res.status(400).send(`Update not possible. Error details: ${err.message}`);
        });
    }).catch(err => {
        res.status(404).send(`Product not found. Error details: ${err.message}`);
    });
})

// Product destroy route (NOT WORKING)
router.delete("/:product_id", function(req, res) {
    Product.find(req.params.product_id).then(product => {
        product.remove().then(product => {
            res.status(200).json(`Product deleted! Deleted product details: ${product}`);
        }).catch(err => {
            res.status(400).send(`Delete not possible. Error details: ${err.message}`);
        });
    }).catch(err => {
        res.status(404).send(`Product not found. Error details: ${err.message}`);
    });
})

module.exports = router;

Error in Postman:

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<title>Error</title>
</head>

<body>
	<pre>Cannot DELETE /products/5e335c57bd37eb1dd4d99b1f</pre>
</body>

</html>

Thank you

Questioner
Andrex
Viewed
84
SuleymanSah 2020-01-31 18:57

find returns an array, and in array there is no remove() method. You need to use findOne. Also find doesn't throw an error when nothing found. So you had better to check if find returns null.

router.delete("/:product_id", function(req, res) {
  Product.findOne(req.params.product_id)
    .then(product => {
      if (product) {
        product
          .remove()
          .then(product => {
            res.status(200).json(`Product deleted! Deleted product details: ${product}`);
          })
          .catch(err => {
            res.status(400).send(`Delete not possible. Error details: ${err.message}`);
          });
      } else {
        res.status(404).send(`Product not found. Error details: ${err.message}`);
      }
    })
    .catch(err => {
      res.status(500).send(`Error details: ${err.message}`);
    });
});

Also you can shorten this code using findByIdAndDelete method like this:

router.delete("/:product_id", function(req, res) {
  Product.findByIdAndDelete(req.params.product_id)
    .then(product => {
      if (product) {
        return res.status(200).json(`Product deleted! Deleted product details: ${product}`);
      } else {
        return res.status(404).send("Product not found");
      }
    })
    .catch(err => {
      res.status(500).send(`Error details: ${err.message}`);
    });
});