I have an API created in Express that connects to the MongoDB database via Mongoose. There are Product records in the database. I need a list of all products in the selected category to be sent in the query path. If I get a GET query /api/products/baseball, I would like to get a list of all products that match the "baseball" category. If I get a GET query /ap/products/tennis, then I would like to receive all products in the category "tennis". How do I accomplish this?
Below is the code I was able to create
With the current code, when I execute the GET query http://localhost:5050/api/products/tenis I get this error:
"message": "Cast to ObjectId failed for value "tennis" at path "_id" for model "Product",
productModel.js:
import mongoose from 'mongoose'
const productSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
name: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
default: 0,
},
category: {
type: String,
},
},
{
timestamps: true,
}
)
const Product = mongoose.model('Product', productSchema)
export default Product
productRoutes.js:
import express from 'express'
const router = express.Router()
import {
getProductsByCategory,
} from '../controllers/productController.js'
router.route('/:category').get(getProductsByCategory)
export default router
productController.js
import asyncHandler from 'express-async-handler'
import Product from '../models/productModel.js'
const getProductsByCategory = asyncHandler(async (req, res) => {
const products = await Product.find({ category: req.params.category })
res.json({ products })
})
export {
getProductsByCategory,
}
server.js
...
app.use('/api/products', productRoutes)
...