You can use mongodb aggregation pipeline
to achieve the same. More specifically you can use $lookup
twice to populate parent
and its parent
, and finally $project
to flatten the structure.
Try this:
Category.aggregation([{
$lookup : {
from :"categories",
localField : "parent",
foreignField : "_id",
as :"parent"
}
},{
$unwind : "$parent"
},{
$lookup : {
from :"categories",
localField : "parent.parent",
foreignField : "_id",
as :"parent.parent"
}
},{
$unwind : "$parent.parent"
},{
$project : {
l1_id : "$_id",
l1_name : "$name",
l2_id : "$parent._id",
l2_name : "$parent.name" ,
l3_id : "$parent.parent._id",
l2_name : "$parent.parent.name"
}
}]).then(result => {
// result will have l1_id, l1_name, l2_id, l2_name, l3_id, l3_name
// where l2 is the parent,
// and l3 is the parent of parent
}).
Note: $unwind
is used after $lookup
stage, as $lookup
returns an array, we need to unwind it to convert it to object.
For more info please read Mongodb $lookup documentation,and $project documentation.
i hope this helps you out.