node.js - 使用 findById 方法时,我应该怎么做才能摆脱猫鼬的 Cast 错误
问题描述
当我使用findById
mongoose 定义的方法时,出现类似这样的 Cast 错误
CastError: Cast to ObjectId failed for value "611411089cb0c839083962ba4" (type string) at path "_id" for model "Product"
at model.Query.exec (/home/user/web/mern/emartwell/node_modules/mongoose/lib/query.js:4498:21)
at model.Query.Query.then (/home/user/web/mern/emartwell/node_modules/mongoose/lib/query.js:4592:15)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
但我需要产品未找到错误。
我指定的路线是
http://localhost:5000/api/products/611411089cb0c839083962ba4
代码
productRoute.js
import express from "express";
import asyncHandler from "express-async-handler";
import Product from "../models/productModel.js";
const router = express.Router();
router.get(
"/:id",
asyncHandler(async (req, res) =>
{
const product = await Product.findById(req.params.id);
if (product)
{
res.json(product);
} else
{
res.status(404).send({ message: "Product not found" });
}
})
);
export default router;
请帮助我摆脱这个问题。先谢谢了
解决方案
检查是否req.params.id
正确。
利用
Product.findOne({ _id : req.params.id }).
exec((error, product) => {
//what ever you want
})
产品路由器
router.get('/getproductById/:id', productController.getProductById_get);
产品控制器
module.exports.getProductById_get = async (req, res) => {
Product.findOne({ _id : req.params.id }).
exec((error, product) => {
if(error) {return res.status(400).json({ error })};
if(product) {
res.status(200).json({ product });
}
})
}
更新
import express from "express";
import asyncHandler from "express-async-handler";
import Product from "../models/productModel.js";
const router = express.Router();
router.get(
'/:id',
asyncHandler(async (req, res) =>
{
const product = await
Product.findOne({_id:req.params.id}).
exec((error,product) => {
if (product)
{
res.json({product});
} else
{
res.status(404).send({ message: "Product not found" });
}
})
);
推荐阅读
- javascript - 如何使用 javascript 更改图像?
- c++ - 为什么 Xcode (10.1) 不实现这个类?我究竟做错了什么
- boost - 无法以编程方式更改提升多精度 mpfr 精度
- sequelize.js - 如何将varchar列与sequelize中日期的时间部分进行比较
- mysql - SQL - MySQL - 如何仅获取其中一列具有相同值的记录
- django - Django:安装夹具的完整性错误
- mysql - 每个表上的“限制”字段,还是所有限制的单个表?
- uber-api - Android 上 Uber Eats 服务的 API 端点是什么?
- ruby-on-rails - 在rails中重定向循环
- ruby-on-rails - 如何在 webpacker 角轨中添加 scss 加载器?