【发布时间】:2020-05-18 16:06:24
【问题描述】:
所以我有下一个架构:
const CategorySchema = new Schema({
name: {
type: String,
required: true,
},
parent: {
type: Schema.Types.ObjectId,
ref: 'Category',
default: null,
},
order: {
type: Number,
required: true,
min: 0,
}
});
所以我想要的是获得下一个输出(为了简单起见,我放了简单的 _ids):
[
{
_id: '1',
name: 'MainCategory1',
parent: null,
order: 0,
children: [
{
_id: '3',
name: 'SubCategory3',
parent: '1',
order: 0,
},
]
},
{
_id: '2',
name: 'MainCategory2',
parent: null,
order: 1,
children: [
{
_id: '4',
name: 'SubCategory1',
parent: '2',
order: 0,
},
{
_id: '5',
name: 'SubCategory2',
parent: '2',
order: 1,
},
]
},
]
那么我怎么能得到这个结果呢?请注意,它必须按“订单”字段排序,对于父母和孩子来说都是如此。
另外,是否可以使用 mongoose 查询而不是聚合来获得此结果?
我知道如果我在 Schema 中存储“children”数组而不是“parent”,这会更简单,但我更喜欢这种方法,因为每个类别只有一个父 ref,并且 doc 不会因数组而变得臃肿的对象。换一种方式,“子”数组可能非常大,我认为如果在搜索时查看一个“父”值,而不是查看“子”数组(可能是 ObjectIds 的 100 多个元素),mongo 的工作速度会更快。
【问题讨论】: