Proper Mongoose Subdocument Relation Proper Mongoose Subdocument Relation mongoose mongoose

Proper Mongoose Subdocument Relation


You can try below aggregation

Group.aggregate([  { "$lookup": {    "from": Invitations.collection.name,    "let": { "invitations": "$invitations" },    "pipeline": [      { "$match": { "$expr": { "$in": [ "$_id", "$$invitations" ] } } }    ],    "as": "invitations"  }},  { "$match": { "invitations.user": user._id } }])

or this

Group.aggregate([  { "$lookup": {    "from": Invitations.collection.name,    "let": { "invitations": "$invitations" },    "pipeline": [      { "$match": {        "user": user._id,        "$expr": { "$in": [ "$_id", "$$invitations" ] }      }}    ],    "as": "invitations"  }},  { "$match": { "invitations.user": user._id } }])

And the last one which I think is the best option to start with User collection

User.aggregate([  { "$match": { "_id": user._id }},  { "$lookup": {    "from": Groups.collection.name,    "let": { "userId": "$_id" },    "pipeline": [      { "$match": { "$expr": { "$eq": [ "$created_by", "$$userId" ] }}}    ],    "as": "groups"  }}])