【问题标题】:How can I get this DELETE route to work in my products.js route?如何让这条 DELETE 路线在我的 products.js 路线中工作?
【发布时间】:2020-01-31 00:07:48
【问题描述】:

我在删除单个产品时遇到问题,方法是在 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;

邮递员错误:

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

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

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

</html>

谢谢

【问题讨论】:

  • 如果你像在更新路由中那样使用“.findById()”而不是“.find()”,它是否有效?
  • 不幸的是,我也遇到了与“.findById()”相同的错误
  • 使用.findById()运行时是否会出现同样的错误?
  • 你为什么不尝试另一种方法,我的意思是findOneAndRemove

标签: javascript node.js mongodb mongoose routes


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多