Jake Starkey
Jake Starkey

Reputation: 65

Mongoose: CastError at path "_id" when ID is not being called

Stack in question: Node, EJS, Mongo, Mongoose

My routing was set up so:

app.get('/products', async (req,res) => {
    const products= await Product.find({});
    res.render('products/index', {products});
})

app.get('/products/:id', async (req,res) =>{
    const {id} = req.params;
    const product = await Product.findById(id);
    res.render('products/show', {product});
})

app.get('/products/new', (req,res)=>{
    res.render('products/new');
})

And I was getting this error:

CastError: Cast to ObjectId failed for value "new" at path "_id" for model "Product"

And I eventually fixed the error by moving the /new route above the /:id route.

My question is: why did that fix it? I wasn't calling {id} in the /new route. The /new route wasn't calling anything except for my EJS file in the res.render. I can't find any reason on the internet why moving the route higher in the code fixed the issue.

Upvotes: 1

Views: 155

Answers (1)

Naveen Chahar
Naveen Chahar

Reputation: 571

When your route 'app.get('/products/:id')' is defined above, it considers every value after '/products/' to be an id param. For example, if you call '/products/new' route, the app.get('/products/:id') route catches the request thinking that the value of id param is 'new' and starts processing the request without allowing it to reach its intended place.

But if you define 'app.get('/products/new')' route before 'app.get('/products/:id')', it will catch any request intended for the '/products/new' route and leave the requests which contains id params.

Upvotes: 1

Related Questions