I'm trying to find products by name and price. It doesn't execute an error at execution time. But I've got error on postman.
I only want is finding name or price from the product.
I put name in one method and price in other as params
this is my product model:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const productSchema = new Schema({
name: String,
description: String,
brand: String,
price: Number,
availableStock: Number,
code: Number,
isPassed: Boolean,
createdAt: Date,
passedAt: Date
});
mongoose.model('products', productSchema);
And these are my product routes
find product by name
app.get('/api/products/:name', async(req,res) =>{
try{
const name = req.params.name;
const product = await Product.findOne({product : name});
if(product){
res.send(product);
}
else{
res.status(404).send({ message: `product's name: '${name}' couldn't be
found ` });
}
}catch (err) {
console.log(err);
res.status(500).send({ message: `Internal Server Error.\n\n${err}` });
}
});
find products by price
app.get('/api/products/:price', async(req,res) =>{
try{
const price = req.params.price;
const products = await Product.find({products : price});
if(products){
res.send(products);
}
else{
res.status(404).send({message:`Products with price: '${price}'
couldn't be found`})
}
}catch (err) {
console.log(err);
res.status(500).send({ message: `Internal server error.\n\n${err}` });
}
});
I expect the product found by name or price, but in the case of name this is the result:
{ "message": "Internal Server Error.\n\nCastError: Cast to ObjectId failed for value \"P1\" at path \"_id\" for model \"products\"" } And by last, In the case of price this is the result:
{ "message": "Internal Server Error.\n\nCastError: Cast to ObjectId failed for value \"500\" at path \"_id\" for model \"products\"" }