获取包含成员数据的组列表,其中用户不是组的成员或所有者

时间:2017-08-03 11:14:58

标签: mongodb mongoose

我有两个像下面的集合,我很困惑的查询可以任何一个请帮助解决,

组:

var WorkKrewSchema = mongoose.Schema({
    content_detail: {
        name: String,
        description: String
    },
    business_info: {
        name: String,
        address: String,
        city: String,
        state: String,
        zipcode: String,
        website: String,
        starting_hours: Date,
        ending_hours: Date,
        days: Array
    },
    created_by: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    created_on: Date,
    updated_on: Date
});

成员:

var KrewPartnerSchema = mongoose.Schema({
    Work_krew_id: {
        type: mongoose.Schema.Types.ObjectId 
    },
    members: [
        {
            refrence_id: mongoose.Schema.Types.ObjectId,
            is_sub_admin: {
                type: Boolean,
                default: false
            },
            status: {
                type: String,
                enum: ['accepted', 'declined', 'pending']
            },
            date_of_join: Date
        }
    ]
});

获取群组:

  • 用户不是该组的所有者,也不是该成员,
  • 如果用户是成员,则状态应为待处理

1 个答案:

答案 0 :(得分:0)

假设您的集合Groups包含以下格式的文档:

{
    "_id" : ObjectId("598311f3c63f57ec3dcac86f"),
    "grp_name" : "groupA",
    "created_by" : "userA"
}

...以及包含以下格式的文档的集合Members

{
    "_id" : ObjectId("59831310c63f57ec3dcac891"),
    "grp_id" : ObjectId("598311f3c63f57ec3dcac86f"),
    "members" : [ 
        {
            "user_id" : "UserY",
            "status" : "pending"
        }, 
        {
            "user_id" : "UserA",
            "status" : "pending"
        }, 
        {
            "user_id" : "UserB",
            "status" : "approved"
        }
    ]
}

...您可以为名为"UserA"的用户运行以下查询,该用户应该执行您需要的操作:

db.getCollection('Members').aggregate(
  {
    $lookup:
    {
      from: "Groups",
      localField: "grp_id",
      foreignField: "_id",
      as: "group"
    }
  },
  {
    $match:
    {
      $or:
      [
        {
          "members.user_id": { $ne: "UserA" },
          "group.0.created_by": { $ne: "UserA" }
        },
        {
          "members":
          {
            $elemMatch:
            {
              "user_id": "UserA",
              "status": "pending"
            }
          }
        }
      ]
    }
  }
)

但我建议您将这两个集合合并为一个集合。组文档应该只包含其所有成员,在这种情况下,您不需要$lookup内容,并且可以使用简单查询(没有聚合框架)。