Currently i have one collection "Category" which has a self join with ref on parent column. In that I have 3 Document.
- Document 1 is the parent.
- Document 2 is the child of Document 1
- Document 3 is the child of Document 2
CategoryModel
var CategoryTable = new Schema({
categoryName : String,
parent : {
type : ObjectID,
ref : 'category',
default : null
}
});
MyCode
CategoryModel
.aggregate([
{
$match : { "parent" : null }
},
{
"$lookup":{
"from" : "categories",
"localField":"_id",
"foreignField":"parent",
"as": "child"
}
}
])
.exec((err,data) => {
if(err)
{
throw err;
}
res.send(data);
})
Current Output
[
{
"_id": "5d8de924b4672e2744dedbb9",
"parent": null,
"categoryName": "Software",
"__v": 0,
"child": [
{
"_id": "5d8de972b4672e2744dedbba",
"parent": "5d8de924b4672e2744dedbb9",
"categoryName": "Antivirus",
"__v": 0
}
]
}
]
Expected Output
[
{
"_id": "5d8de924b4672e2744dedbb9",
"parent": null,
"categoryName": "Software",
"__v": 0,
"child": [
{
"_id": "5d8de972b4672e2744dedbba",
"parent": "5d8de924b4672e2744dedbb9",
"categoryName": "Antivirus",
"__v": 0,
"child": [
{
"_id": "5d8e1a303bcfb6085c48e4dc",
"parent": "5d8de972b4672e2744dedbba",
"categoryName": "Quick Heal",
"__v": 0
}
]
}
]
}
]
I want to fetch all the child and subchild collection using aggregate. Can someone please help me in this?