0

I'm trying to "match" a referenced document (populated) with the parent document id. The goal is to only show members permissions for the specific organization and not all the other permissions they may have. So the 'entity.item', in this case an organization, would have to match the parent organization id. I'm trying to find out how, if possible, to access the parent organization id from a child doc.

let userId = '123';
let organizations = await Organization.find().where('members.includes(userId)').populate({
    path: 'members',
    options: { sort: { name: 1 } },
    populate: {
      path: 'permissions',
      match: {
        'entity.kind': 'Organization',
        'entity.item': organization._id  //HERE
      },
      populate: {
        path: 'entity.item'
      }
    }
  });
half0636
  • 21
  • 4
  • Have you tried using this._id instead of organization._id? Also you don't need to repopulate the entity.item as it's already available in the parent document. If that doesn't work then you'll probably have to use aggregation to achieve this. – Firoz Shams Jan 06 '19 at 09:40
  • Thanks @FirozShams for telling me to look into aggregation. I'm pretty new still to Mongo so I hadn't learned that yet. I'll update my question after I do some testing. Thanks again. – half0636 Jan 08 '19 at 05:03

1 Answers1

0

I ended up using the lookup operator on the aggregate method. Still testing use cases but seems to be working. The following answer pointed me in that direction.

"With the mongodb 3.6 and above $lookup syntax it is quite simple to join nested fields without using $unwind."

let organizations = await Organization.aggregate([
  { $sort: { name: 1 } },
  { $match: { $expr: { $in: [ user.id, '$members' ] } } },
  {
    $lookup: {
      from: 'user',
      let: { id: '$_id', members: '$members' },
      pipeline: [
        { $match: { $expr: { $in: [ '$_id', '$$members' ] } } },
        { $addFields: { id: '$_id' } },
        {
          $lookup: {
            from: 'permission',
            pipeline: [
              { $match: { $expr: { $and: [
                { $eq: [ '$entity.kind', 'Organization' ] },
                { $eq: [ '$entity.item', '$$id' ] }
              ] } } },
              { $addFields: { id: '$_id' } },
              {
                $lookup: {
                  from: 'organization',
                  pipeline: [
                    { $match: { $expr: { $eq: [ '$_id', '$$id' ] } } },
                    { $addFields: { id: '$_id' } }
                  ],
                  as: 'entity.item'
                }                      
              }
            ],
            as: 'permissions'
          }
        }
      ],
      as: 'members'
    }
  },
  { $addFields: { id: '$_id' } }
]);
half0636
  • 21
  • 4