1

I'm querying an object from a collection that has a key with an array of objects. I want it to return the object and exclude the elements in the array that have "available: false".

Ex:

{
  name: "Willy's Store",
  city: "Baigorria",
  storeId:"666",
  open: [
    {day: monday, available: true}, 
    {day: tuesday, available:true}, 
    {day:wensday, available: true},
    {day:thursday, available:false}, 
    {day:friday, available:false}
  ]
}

on the query, the expected result should be

{
  name: "Willy's Store",
  city: "Baigorria",
  storeId:"666",
  open: [
    {day: monday, available: true}, 
    {day: tuesday, available:true}, 
    {day:wensday, available: true}
  ]
}

I want to only use mongoose to achieve it

BlowFish
  • 326
  • 4
  • 10
  • 1
    I think this is a similar question to this https://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb, you can use the aggregate function to match the object 'Willy's Store' and then $unwind to access the array values (open) and match `available != false` then group them back together with $group. – Chris Parry Dec 17 '21 at 14:24
  • I've updated my example to be more precise. Using the aggregation proposed in that post, i don't get back the "city" and "storeId" or even the "name", only the open array that match the "available: true" condition with "_id" – BlowFish Dec 17 '21 at 15:14
  • The scenario uses the unwind and group to put it back, I'd suggest trying it. – Chris Parry Dec 17 '21 at 17:04
  • yes i did, it doesn't bring the rest of the data back. only the filtered data. – BlowFish Dec 17 '21 at 17:11

1 Answers1

0

You can use filter concept of arrays on open object to filter out available days.

    var data = {
    "name": "Willy's Store",
    "open": [{
        "day": "monday",
        available: true
    }, {
        "day": "tuesday",
        available: true
    }, {
        "day": "wensday",
        available: true
    }, {
        "day": "thursday",
        available: false
    }, {
        "day": "friday",
        available: false
    }]
}
data.open = data.open.filter(subData => subData.available)
console.log(data)
Deepak
  • 2,660
  • 2
  • 8
  • 23
  • yes, this is what i currently do. I believe it can be done using mongoose which i would find a cleaner approach. Thank you. – BlowFish Dec 17 '21 at 14:29
  • Great. Then I believe the comment of [@ChrisParry](https://stackoverflow.com/users/1871154/chris-parry) would be a try. – Deepak Dec 17 '21 at 14:32
  • I've updated my example to be more precise. Using the aggregation proposed in that post, i don't get back the "city" and "storeId" or even the "name", only the open array that match the "available: true" condition with "_id" – BlowFish Dec 17 '21 at 15:14