Marya
Marya

Reputation: 123

mongoose: filtering based on a populated field

I have a schema called BeansSchema which has this field:

roaster: {
  type: mongoose.Schema.Types.ObjectId,
  ref: "Roaster",
  required: [true, "roaster is required"],
}

because I want it in several places I'm populating it in all find() queries:

BeanSchema.pre(/^find/, function(next) {
 this.populate({path: "roaster", select: "nameEn nameAr image slug"});
 next();
});

until here everything is fine and working as expected. now I'm implementing the filtering logic and I have been struggling and can't wrap my head around the way of filtering the bean based on the roaster's name, I googled a lot and tried many things but none worked at all

here is the query where I want to perform the desired filter:

export async function getAll(Model, filter = {}, sortBy = "-ratingsAverage") {
  
  if(sortBy === "-ratingsQuantity" || sortBy === "ratingsQuantity") {
    sortBy = sortBy.concat(" -ratingsAverage nameAr")
  }
  
  try {
    await dbConnection();

    const docs = await Model.find(filter).sort(sortBy).populate({path: "roaster", match: {'nameEn': {$in: ["soil"]}}});

    if(!docs) return "No matched data";

    return JSON.parse(JSON.stringify(docs));

  } catch (error) {
    console.log("getAll", error);
  }

}

I can print the roaster field so the populate itself has nothing to do with this problem, right? no matter what I did it seems any condition I wrote for the roaster inside populate() or find() didn't have any effect on the final result, I don't have any clue why is that.

I'll appreciate your help 🙏

Upvotes: 0

Views: 40

Answers (0)

Related Questions