mongodb - 在mongoose中使用Self join从单个集合中获取所有孙子
问题描述
目前我有一个集合“类别”,它在父列上有一个与 ref 的自联接。在那我有3个文件。
- 文档 1 是父级。
- 文档 2 是文档 1 的孩子
- 文档 3 是文档 2 的子文档
类别型号
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
}
]
}
]
}
]
我想使用聚合来获取所有子集合和子集合。有人可以帮我吗?
解决方案
推荐阅读
- angular - Sanitizer Angularerror TS2339:“Sanitizer”类型上不存在属性“bypassSecurityTrustUrl”
- html - 引导按钮文本未调整大小
- google-analytics - Firebase 更改后的 Google Analytics for desktop 应用程序
- swift - 按下表格视图单元格
- c - 按位运算的 CLion“表达式可以简化”消息
- c++ - 无法将左值绑定到转发引用
- ruby - 如何更改 Pry 中对象的输出颜色?
- nodes - 一个节点代表一个用户还是多个用户?
- c# - 用 Linq 替换嵌套循环
- objective-c - AppDelegate 从 m File + presentViewController 调用函数