Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
How to return all documents matching API path in mongoose?

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)
...
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!