Reputation: 43
import express from 'express'
import asyncHandler from 'express-async-handler'
import Product from '../models/productModel.js'
const router = express.Router()
router.get('/',asyncHandler(async (req, res) => {
const products = await Product.find({})
res.json(products)
}))
router.get('/:id',asyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id).exec()
if(product)
{
res.json(product)
}
else{
res.status(404).json({message: 'Not found'})
}
}))
export default router
Rest code is working. But when I intentionally put the wrong id, error 404 is not displayed. The Error part is this.
Upvotes: 1
Views: 233
Reputation: 24555
The error happens because you pass an id
-value to mongoose that cannot be cast to ObjectId
, hence the error "Cast to ObjectId failed for value". You can prevent passing invalid object-ids using the following check and handle this case accordingly, e.g.:
import mongoose from "mongoose";
router.get('/:id',asyncHandler(async (req, res) => {
if( !mongoose.isValidObjectId(req.params.id) ) {
return res.status(404).json({message: 'Not found'});
}
// rest of the code
});
Upvotes: 2