首页 > 解决方案 > 在mongoose中使用Self join从单个集合中获取所有孙子

问题描述

目前我有一个集合“类别”,它在父列上有一个与 ref 的自联接。在那我有3个文件。

类别型号

var CategoryTable = new Schema({
categoryName : String,
parent : {
    type : ObjectID,
    ref : 'category',
    default : null
}
});

我的代码

CategoryModel
    .aggregate([
        {
            $match : { "parent" : null }
        },
        {
            "$lookup":{
                "from" : "categories",
                "localField":"_id",
                "foreignField":"parent",
                "as": "child"
            }
        }
    ])
    .exec((err,data) => {
        if(err)
        {
            throw err;
        }
        res.send(data);
    })

电流输出

[
{
    "_id": "5d8de924b4672e2744dedbb9",
    "parent": null,
    "categoryName": "Software",
    "__v": 0,
    "child": [
        {
            "_id": "5d8de972b4672e2744dedbba",
            "parent": "5d8de924b4672e2744dedbb9",
            "categoryName": "Antivirus",
            "__v": 0
        }
    ]
}
]

预期产出

[
{
    "_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
                         }
                    ]
        }
    ]
}
]

我想使用聚合来获取所有子集合和子集合。有人可以帮我吗?

标签: mongodbmongooseaggregation-frameworkaggregatelookup

解决方案


推荐阅读