首页 > 解决方案 > 使用 findById 方法时,我应该怎么做才能摆脱猫鼬的 Cast 错误

问题描述

当我使用findByIdmongoose 定义的方法时,出现类似这样的 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;


请帮助我摆脱这个问题。先谢谢了

标签: node.jsmongodbexpressmongoose

解决方案


检查是否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" });
        }
    })
);

推荐阅读