Friday 21 April 2017

Mongoose: only show populated results

I'm trying to return a result that is filtered by populate

Schema for a collection

{
  myObjects: [{
    obj: { type: Schema.ObjectId, ref: myObject }
  }]
}

Schema for myObject

{
  name: { type: String },
  active: { type: Boolean }
}

So

.find().populate('myObjects.obj')

This returns back results like so

[
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }, 
      { obj: { name: 'Stacy', active: false } },
      { obj: { name: 'James', active: false } }
    ]
  },
  { myObjects: 
    [
      { obj: { name: 'James', active: false } }
    ]
  },
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }
    ]
  },
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }, 
      { obj: { name: 'James', active: false } }
    ]
  }
]

At this point, I want to say "Only show me those where active: true"

so I do...

.find().populate({ path: 'myObjects.obj', match: { active: true })

Except this returns back the following

[
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }
    ]
  },
  { myObjects: 
    [

    ]
  },
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }
    ]
  },
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } } }
    ]
  }
]

There's one myObjects that contains an empty array. How do I exclude this from the result so I'm only receiving back

[
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }
    ]
  },
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } }
    ]
  },
  { myObjects: 
    [
      { obj: { name: 'Adam', active: true } } }
    ]
  }
]



via BpH

No comments:

Post a Comment