javascript - 如何让此 DELETE 路由在我的 products.js 路由中工作?

标签 javascript node.js mongodb mongoose routes

我在通过获取 Mongoose 中的 _id (5e335c57bd37eb1dd4d99b1f) 来删除单个产品时遇到问题。我认为简单地复制更新路线并稍微改变一下就可以了。所有其他路线在 Postman 中都工作正常。

产品.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>

谢谢

最佳答案

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

关于javascript - 如何让此 DELETE 路由在我的 products.js 路由中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59996309/

相关文章:

javascript - 对话框淡出离开边界框

javascript - 如何在 Node 中的文本中替换/注入(inject) html 标签?

node.js - 如何通过 REST Api 在环回中使用 Decimal128

mongodb - 在 MongoDB 中创建新元素时显示对象而不是 db-ref ObjectId

javascript - 在 Javascript 中检查所有复选框第二次不起作用

javascript - 在 ES6 类数组中调用带有回调的方法

javascript - 学习 MongoDB 如何使用 2 个集合中的数据进行查找

MongoDB 检查属性是否存在(以及子属性)

javascript - 通过webrtc传递上传的图片 - pubnub

node.js - Socket.io app ...我应该使用emit还是使用常规http请求并用express处理它?