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

165
Vistas
problem getting data in mongodb, get by category id

I'm trying to filter my pets by category, I have the following model of pets:

const Pet = mongoose.model(
    'Pet',
    new Schema({
        name: {
            type: String,
            required: true,
        },
        age: {
            type: Number,
            required: true,
        },
        description: {
            type: String,
        },
        weight: {
            type: Number,
            required: true,
        },
        color: {
            type: String,
            required: true,
        },
        images: {
            type: Array,
            required: true,
        },
        available: {
            type: Boolean,
        },
        category: Object,
        user: Object,
        adopter: Object,
    }, { timestamps: true }),
);

module.exports = Pet;

when I try to get the data through postman it returns an empty array as a response.

my code to filter by category:

static async getByCategory(req, res) {

        const id = req.params.id;

        // check if id is valid
        if (!ObjectId.isValid(id)) {
            res.status(422).json({ msg: 'Invalid ID' });
            return;
        }

        const pets = await Pet.find({ 'category._id': id }).sort('-createdAt');

        if (!pets) {
            res.status(404).json({ msg: 'Pets not found!' });
            return;
        }

        res.status(200).json({ pets });
    }

it's my first time using mongodb so i'm not sure what's wrong.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Could you check that your MongoDB indeed has a field category._id?

about 4 years ago · Juan Pablo Isaza Denunciar

0

id being passed from the client side is string and the one which is saved in the db is ObjectId. Convert the string to Mongoose ObjectId before Pet.find().

const id = mongoose.Types.ObjectId(req.params.id);

const pets = await Pet.find({ 'category._id': id }).sort('-createdAt');

Don't forget to import 'mongoose'.

about 4 years ago · Juan Pablo Isaza Denunciar
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