0

I have a roles collection whose schema is like this :

{ name:String, parent:{type:Schema.Types.ObjectId, ref:"role"} }

it has 3 documents right now as shown below

    {
        "_id": "5d6ba446efbe40d83dca94a6",
        "name": "Super Admin", 
        "__v": 0
    },
    {
        "_id": "5d6ba446efbe40d83dca94a8",
        "name": "Moderator", 
        "__v": 0,
        "parent": "5d6ba446efbe40d83dca94a6"
    },
    {
        "_id": "5d6ba446efbe40d83dca94aa",
        "name": "Worker",
        "__v": 0,
        "parent": "5d6ba446efbe40d83dca94a8"
    }

i have another collection users whose schema looks like this:

{ name:String, role:{type:Schema.Types.ObjectId, ref:"role"} }

It has 2 document as shown below

{
    "_id": "5d6ba540bda3f0191c7295a9",
    "name": "User 1",
    "role": "5d6ba446efbe40d83dca94a6"
}
{
    "_id": "5d6bb69e17761518640385df",
    "name": "User 2",
    "role": "5d6ba446efbe40d83dca94a8"
}

User 1 is assigned a role of Super Admin and User 2 is assigned a role of Moderator

I've tried this

User.aggregate([
        {
            $graphLookup: {
                from: "roles",
                startWith: "$role",
                connectFromField: "_id",
                connectToField: "parent",
                as: "reportsTo",
                maxDepth: 0
            }
        }
    ])

but i ended up getting result like this :

[
        {
            "_id": "5d6ba540bda3f0191c7295a9",
            "name": "User 1",
            "role": "5d6ba446efbe40d83dca94a6",
            "reportsTo": [
                {
                    "_id": "5d6ba446efbe40d83dca94a8",
                    "name": "Moderator",
                    "__v": 0,
                    "parent": "5d6ba446efbe40d83dca94a6"
                }
            ]
        },
        {
            "_id": "5d6bb69e17761518640385df",
            "name": "User 2",
            "role": "5d6ba446efbe40d83dca94a8",
            "reportsTo": [
                {
                    "_id": "5d6ba446efbe40d83dca94aa",
                    "name": "Worker",
                    "__v": 0,
                    "parent": "5d6ba446efbe40d83dca94a8"
                }
            ]
        }
]

I want the result as given below, based on the hierarchy defined in roles collection

{
    "_id": "5d6ba540bda3f0191c7295a9",
    "name": "User 1",
    "role": "5d6ba446efbe40d83dca94a6",
    "reportsTo": []
}
{
    "_id": "5d6bb69e17761518640385df",
    "name": "User 2",
    "role": "5d6ba446efbe40d83dca94a8"
    "reportsTo": [
        {
            "_id":"5d6ba540bda3f0191c7295a9",
            "name":"User 1",
            "role":"5d6ba446efbe40d83dca94a6"
        }
    ]
}

How can i get the expected result?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.