Snehil Kumar
Snehil Kumar

Reputation: 43

I am getting internal error 500 instead of 404 in mongoose when using res.json()

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. enter image description here

Upvotes: 1

Views: 233

Answers (2)

eol
eol

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

wangdev87
wangdev87

Reputation: 8751

Use exec() method. Refer to here

const product = await Product.findById(req.params.id).exec()

Upvotes: 0

Related Questions