Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda