What should I do to get rid of the Cast error by mongoose when using the findById method

Viewed 211

when I using the findById method defined by mongoose , I got a Cast error something like this

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)

But I need the product not found error.

the route I specified is

http://localhost:5000/api/products/611411089cb0c839083962ba4

Code

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;


Please help me to get rid of this problem. Thanks in advance :D

1 Answers

check if req.params.id is correct .

use

 Product.findOne({ _id : req.params.id }).
  exec((error, product) => {
//what ever you want
})

ProductRouter

router.get('/getproductById/:id', productController.getProductById_get);

ProductController

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

update

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" });
        }
    })
);
Related