【发布时间】:2020-11-13 16:35:47
【问题描述】:
这是类别集合的架构,我在其中存储类别、子类别和子类别的更多子项。
mongoose.Schema({
name:{ type: Array, required: true}, //It is an array because name can be in multiple languages
path:{ type: String, required: true}, // All parent categories in an order to have immediate parent at the end
parent: { type: String, required: true}
});
我已经为所有三个字段添加了索引。现在,要求是 - 需要将所有子类别嵌套在作为单个查询的结果返回的父类别数组中。
对于根类别,parent 具有 '/' 和 path 是“/”分隔的 ID,直到直接父级。
我尝试的是,通过传递_id 来获取父类别的所有子类别,Like -
categoryModel.find({parent: /^\/documentId/})
但是,我希望结果中包含嵌套在其中的子类别的所有父类别。该怎么做?
预期输出 -
[
{
_id: '1',
name: 'MainCategory1',
path: '/'
parent: '/',
children: [
{
_id: '3',
name: 'SubCategory3',
parent: '1',
path: '/1'
},
]
},
{
_id: '2',
name: 'MainCategory2',
path: '/'
parent: '/',
children: [
{
_id: '5',
name: 'SubCategory5',
parent: '2',
path: '/2',
children: [
{
_id: '7',
name: 'SubCategory7',
parent: '5',
path: '/2/5',
children: [
{
_id: '9',
name: 'SubCategory7',
parent: '7',
path: '/2/5/7',
}]
},
]
},
]
},
]
【问题讨论】:
-
你能放一些示例数据吗,你已经发布了预期的结果。示例数据会有所帮助。
标签: mongodb aggregation-framework