Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda