Skip to content Skip to sidebar Skip to footer

Using $graphlookup To Traverse A Nested Data Structure In Mongodb

I have the following schema: const MenuSchema = new mongoose.Schema({ name: String, type: String, children: [{ type: ObjectId, ref: 'Menu' }], }); And the following query: c

Solution 1:

I don't know if you are still looking for the answer for this, but if you use mongoose you can take advantage of the populate feature and use it as a middleware

Here's an example: Let's say I want a list of people and their friends, and their friends-friends, etc. The result should look like this:

[
    {
        _id: "abc123",
        name: "John Doe",
        friends: [
            {
                _id: "efg456",
                name: "Foo bar",
                friends: [
                    {
                        _id: "hij789",
                        name: "Jane Doe",
                        friends: [more friends...]
                    }
                ]
            }
        ]
]

In the db they are stored like this

{_id: "abc123", name: "John Doe", friends: ["efg456"]}
{_id: "efg456", name: "Foo bar", friends: ["hij789"]}
{_id: "hij789", name: "Jane Doe", friends: [more friends...]}

Your schema and middleware would be:

constPerson = newSchema<Folder>({
    name: {type: String, required: true},
    friends: [{type: Schema.Types.ObjectId, ref: "person"}],
}, {timestamps: true})

Person.pre("find", function(next) {
    this.populate("friends")
    next()
})

Adding the function as a middleware to find will make it run for every person found. That includes the children in the friends array.

Post a Comment for "Using $graphlookup To Traverse A Nested Data Structure In Mongodb"