查询和映射 one-way 从 parent 引用 children 和 sub-children,在 Keystone.js 中使用 mongoose

Query and map one-way referenced children and sub-children from a parent with mongoose in Keystone.js

我得到了三个具有 one-to-many 关系的模型。简单的树。我需要的是一种查询结构化关系树的简单、有效的方法,最好类似于 mongoose 的 .populate(),我不能使用它,因为我在 parent模特。我想在 parent 上保留 children id 会很有效,但 Keystone 默认不提供此功能,我无法编写更新回调来控制关系更改。我尝试并浪费了太多时间,发现自己误入歧途,而也许我想要实现的目标要容易得多,但我就是看不到它。

这是剥离的代码:

类别模型

Category.add({
    name: { type: String}
});
Category.relationship({ path: 'sections', ref: 'Section', refPath: 'category' });

部分模型,child 类别

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'});

文章模型,child 部分

Article.add({
    name: { type: String, required: true}
    section: { type: Types.Relationship, ref: 'Section', many: false }
});

我想获得一个类别的结构化视图,其中包含所有 children 及其各自的 sub-children,如下所示:

[ { _id: 57483c6bad451a1f293486a0,
    name: 'Test Category',
    sections: [
        { _id: 57483cbbad451a1f293486a1,
        name: 'Test Section',
        articles: [ 
            { _id: 57483c6bad451a1f293486a0,
             name: 'Test Category' } 
        ]
    ]
} ]

我就是这样做的。一点也不高效,但至少它在工作。我没有在一级父级中放任何东西,因为我只需要一个。

// Load current category
view.on('init', function (next) {

    var q = keystone.list('Category').model.findOne({
        key: locals.filters.category
    });

    q.exec(function (err, result) {

        if (err || !results.length) {
            return next(err);
        }

        locals.data.category = result;
        locals.section = locals.data.category.name.toLowerCase();           
        next(err);
    });

});


// Load sections and articles inside of them
view.on('init', function (next) {
    var q = keystone.list('Section').model.find().where('category').in([locals.data.category]).sort('sortOrder').exec(function(err, results) {

        if (err || !results.length) {
            return next(err);
        }

        async.each(results, function(section, next) {
            keystone.list('Article').model.find().where('section').in([section.id]).sort('sortOrder').exec(function(err, articles){
                var s = section;
                if (articles.length) {
                    s.articles = articles;
                    locals.data.sections.push(s);
                } else {
                    locals.data.sections.push(s);
                }
            });             

        }, function(err) {
            next(err);
        });

        next(err);
    });
});

但现在我遇到了另一个问题。我使用 Jade 1.11.0 作为模板,有时 它不在视图中显示数据。 我会 post 这个问题的另一个问题。