【发布时间】: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