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

163
Views
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 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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 Report
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!