温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How can I get this DELETE route to work in my products.js route?

javascript - 如何在我的products.js路由中使用此DELETE路由?

发布于 2020-03-29 21:52:40

我在通过Mongoose中的_id(5e335c57bd37eb1dd4d99b1f)来删除单个产品时,让删除路径正常工作时遇到问题。我认为只需复制更新路由并对其进行一些更改即可。其他所有路线在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;

Postman 中的错误:

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

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

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

</html>

谢谢

查看更多

提问者
Andrex
被浏览
66
SuleymanSah 2020-01-31 18:57

find返回一个数组,并且在数组中没有remove()方法。您需要使用findOne当未找到任何内容时,find不会抛出错误。因此,您最好检查find是否返回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}`);
    });
});

您也可以使用findByIdAndDelete方法缩短此代码,如下所示:

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

发布
问题

分享
好友

手机
浏览

扫码手机浏览