首页 > 解决方案 > mongo db inner join + 过滤加入文件

问题描述

我有 3 个文档:边界、角色和用户,每个用户有多个角色和一个边界,每个角色有 1 个边界。用户:

{
  uuid: String,
  name: String,
  rolesBoundary: [
                   roles: [String], // this is the roles the user has for this boundary
                   boundary: String // this is the uuid of the boundary
                 ]
}

角色:

{
  uuid: string,
  name: String
}

边界:

{
  name: String,
  uuid: String
}

我想显示一个边界列表,并且我想再包含一个字段,即登录用户的角色。这是我到目前为止所做的:

{
  await BoundaryModel.aggregate([
        {
            $graphLookup: {
                from: 'users',
                startWith: '$uuid',
                connectFromField: 'uuid',
                connectToField: 'boundaryAccess.roles',
                as: 'roles'
            }
        }
    ]);
}

我知道这是错误的,因为我没有过滤登录用户并且角色数组为空。请问有什么建议吗?

标签: mongodbmongoose

解决方案


通过几次尝试找到了它,我不应该使用图形查找,而是使用查找

exports.getUserBoundaries = async (id) => {
const boundariesList = await BoundaryModel.aggregate()
    .lookup({
        from: "users",
        localField: "uuid",
        foreignField: "rolesBoundary.boundary",
        as: "user_doc"
    })
    .match({
        $or: [
            {"user_doc.uuid": {$exists: false}}, // get result even if the boundary 
                                                 // doesn't have a uuid which is what  
                                               // I want because I want all boundaries
            {"user_doc.uuid": id} // and we get also the boundaries with current user id
        ]
    })

推荐阅读