pat
pat

Reputation: 3593

Querying multiple sub-document elements in Mongoose

I can't seem to get the following query to work:

Group.find({ $or: [ {'groupOwner': req.user._id }, { 'subscribers.user': req.user._id, 'subscribers.level': 'owner' } ] }, 'groupName', { sort: ['groupName', 'ascending'] }, function(err, groups) {

My schema has a Group, with subscribers as a subdocument array. I want to find all groups where the groupOwner matches the passed user ID (works fine), and all documents where subscribers.user = req.user._id AND subscribers.level = 'owner'

The query as written returns all subdocuments where subscribers.user = req.user._id OR there is some subscriber with level = 'owner'. To be clear, I only want groups where subdocument has subscribers.user = req.user._id AND THE SAME SUB-DOCUMENT has subscribers.level = 'owner'.

I've tried all manner of $and and $elemMatch and just can't get it. Thanks for any help!

Upvotes: 2

Views: 2451

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

$elemMatch is the right operator when matching multiple fields in the same array element; your query should look like:

Group.find(
  { $or: [ 
    { groupOwner: req.user._id }, 
    { subscribers: { $elemMatch: { user: req.user._id, level: 'owner' }}}
  ]}, 
  'groupName', 
  { sort: ['groupName', 'ascending'] }, 
  function(err, groups) { ...

Upvotes: 7

Related Questions