3

I have a mongoose schema like this:

var Address = {
    doorNo:String,
    city:String,
    state:String,
    country:String,
    district:String,
    zipCode:String,
    area:String,
    locality:String
};

var StoreSchema = {
    name:String,
    address:Address,
    category:[String],
    products:[{ type:Schema.ObjectId, ref:"Product" }], 
};

var ProductSchema = {
    name:String,
    description:String,
    category:String,
    subCategory:String,
    store: { type:Schema.ObjectId, ref:"Store", childPath:"products" }
};

I need to filter products based on product-category and address-city. Get only those products which belong to a particular location(city in address schema) and a particular category.

I tried the following code:

Product
  .find({'category':'accessories'})
  .populate({
    path: 'store',
    match: { 'address.city': req.params.location},
    select:'_id'

})

Now this returns all the products where category matches but wherever the location filter is not-satisfied it returns a store with null and returns store wherever location filter is satisfied.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
Puneet
  • 654
  • 1
  • 8
  • 16

3 Answers3

1

In Mongoose 5.2.7 the syntax match: { 'x.y': 'something' } works as a charm

o.z
  • 1,086
  • 14
  • 22
  • Can you give a full example of this syntax? Which `populate` did you call, the [model](https://mongoosejs.com/docs/api.html#model_Model.populate) or the document? Which options type, positional, or object? – Dan Dascalescu Apr 21 '20 at 23:37
1

Stated in the documentation here: https://mongoosejs.com/docs/populate.html#query-conditions

The solution should be:

Product
  .find({...})
  .populate({
    ...
    match: { 'city': req.params.location},
    ...
})

You don't need to do 'address.city' just match: { 'city': req.params.location}

Michael Ninh
  • 772
  • 2
  • 10
  • 23
-1

May be you can try this, it worked for me this way.

Product
  .find({ category: 'accessories' })
  .populate({
    path: 'store', 
    model: 'Store', 
    match: {
      address.city: { $eq: 'YOUR_CITY' }
    }
  })
  .exec(function (err, res){})
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Narendra
  • 151
  • 2
  • 12
  • How did that work for you when it wasn't even valid syntax [before](https://stackoverflow.com/revisions/58099485/1) I edited it? – Dan Dascalescu Apr 21 '20 at 23:36