【问题标题】:How can I populate and then match based on the 'parent' id如何根据“父”ID 进行填充然后匹配
【发布时间】:2019-01-12 04:38:45
【问题描述】:

我正在尝试将引用文档(已填充)与父文档 ID“匹配”。目标是仅显示特定组织的成员权限,而不是他们可能拥有的所有其他权限。因此,“entity.item”(在本例中为组织)必须与父组织 ID 匹配。我正在尝试找出如何(如果可能)从子文档访问父组织 ID。

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'
      }
    }
  });

【问题讨论】:

  • 您是否尝试过使用 this._id 而不是 organization._id?此外,您不需要重新填充 entity.item,因为它已经在父文档中可用。如果这不起作用,那么您可能必须使用聚合来实现这一点。
  • 感谢@FirozShams 告诉我要研究聚合。我对 Mongo 还是很陌生,所以我还没有学会。做一些测试后,我会更新我的问题。再次感谢。

标签: javascript mongodb mongoose mongoose-populate


【解决方案1】:

我最终在聚合方法上使用了查找运算符。仍在测试用例,但似乎正在工作。以下答案为我指明了这个方向。

"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' } }
]);

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2021-12-17
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多