Mongoose populate with filter

Viewed 1288

My schema:

const ProductSchema = new Schema({
    Category: String,
    Subcategory: String,
    Name: String,
    Offers: [{ type: ObjectId, ref: "Offer" }]
})

const OfferSchema = new Schema({
    Quantity: Number,
    Images: [String],
    Price: Number,
    Size: String,
    Color: String
})

I am doing query for products with filter offers with limit and skip. I tried this:

const products = await ProductSchema.find({ ...someFilter }).populate({
    path: "Offers",
    match: {
        Quantity: { $gt: 2 },
        Images: { $exists: true, $ne: [] }
    }
}).skip(skip).limit(limit)

And I want to get only documents where length of offers is > 0. But I get documents with empty Offers. If I filter like this:

products.filter(item => item.Offers.length > 0)

My pagination will break. Can you help me?

1 Answers

Just require the Offers field to not be empty like so:

const products = await ProductSchema.find(
    {
        ...someFilter,
        "Offers.0": {$exists: true}
    }
).populate({
    path: "Offers",
    match: {
        Quantity: {$gt: 2},
        Images: {$exists: true, $ne: []}
    }
}).skip(skip).limit(limit)
Related