【发布时间】:2016-09-27 15:45:02
【问题描述】:
我得到了三个具有一对多关系的模型。简单的树。我需要的是一种简单、有效的查询结构化关系树的方法,最好类似于猫鼬的 .populate() ,因为我在父模型上没有 id,所以我不能使用它。我想在父级上保留子级 ID 会很有效,但 Keystone 默认不提供此功能,我无法编写更新回调来控制关系更改。我尝试并浪费了太多时间,发现自己误入歧途,而也许我想要实现的目标要容易得多,但我就是看不到。
这是剥离的代码:
类别模型
Category.add({
name: { type: String}
});
Category.relationship({ path: 'sections', ref: 'Section', refPath: 'category' });
部分模型,类别的子项
Section.add({
name: { type: String, unique: true, required: true}
category: { type: Types.Relationship, ref: 'Category', many: false}
});
Section.relationship({ path: 'articles', ref: 'Article', refPath: 'section'});
文章模型,该部分的子项
Article.add({
name: { type: String, required: true}
section: { type: Types.Relationship, ref: 'Section', many: false }
});
我想获得一个包含所有子项及其各自子项的类别的结构化视图,如下所示:
[ { _id: 57483c6bad451a1f293486a0,
name: 'Test Category',
sections: [
{ _id: 57483cbbad451a1f293486a1,
name: 'Test Section',
articles: [
{ _id: 57483c6bad451a1f293486a0,
name: 'Test Category' }
]
]
} ]
【问题讨论】:
标签: javascript node.js mongodb mongoose keystonejs