MongoDB列出父类别中的子类别
所以我有下一个模式:MongoDB列出父类别中的子类别,mongodb,mongoose,Mongodb,Mongoose,所以我有下一个模式: const CategorySchema = new Schema({ name: { type: String, required: true, }, parent: { type: Schema.Types.ObjectId, ref: 'Category', default: null, }, order: { type: Numbe
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,
}
});
所以我想要的是获得下一个输出(为了简单起见,我放置了简单的ID):
那我怎么能得到这个结果呢?请注意,它必须按“顺序”字段排序,对于家长和孩子也是如此
另外,是否可以使用mongoose查询而不是聚合来获得此结果
我知道如果我在模式中存储“children”数组而不是“parent”,这可能会更简单,但我更喜欢这种方法,因为每个类别只有一个parent的ref,doc不会因为objectid数组而膨胀。另一方面,“children”数组可能非常庞大,我认为如果mongo在搜索时查看一个“parent”值,而不是查看“children”数组,它可能是objectid的100多个元素。这里无法使用常规的
.find()
,但您可以利用聚合框架的以下优势:
[
{
_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,
},
]
},
]
let Category = mongoose.model('Category', CategorySchema);
let result = await Category.aggregate([
{
$sort: { order: 1 }
},
{
$graphLookup: {
from: 'categories',
startWith: '$_id',
connectFromField: '_id',
connectToField: 'parent',
as: 'children'
}
},
{
$match: {
parent: null
}
}
]);