Home > OS >  problem getting data in mongodb, get by category id
problem getting data in mongodb, get by category id

Time:11-18

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;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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 });
    }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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

CodePudding user response:

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'.

  • Related