Keystone.js过滤自己模型中的相关字段

时间:2016-12-14 20:28:11

标签: keystonejs

我正在尝试过滤我的子部分选择,以仅显示与当前mainNavigationSection相关的子部分。这些小节中的每一个都有一个mainNavigation部分。由于某种原因,当前的实现没有返回任何结果。

这是我的页面模型:

Page.add({
  name: { type: String, required: true },
  mainNavigationSection: { type: Types.Relationship, ref: 'NavItem', refPath: 'key', many: true, index: true },
  subSection: { type: Types.Relationship, ref: 'SubSection', filters: { mainNavigationSection:':mainNavigationSection' }, many: true, index: true, note: 'lorem ipsum' },
  state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true },
  author: { type: Types.Relationship, ref: 'User', index: true }
}

这是我的subSectionModel:

SubSection.add({
  name: { type: String, required: true, index: true },
  mainNavigationSection: { type: Types.Relationship, ref: 'NavItem', many: true, required: true, initial: true},
  showInFooterNav: { type: Boolean, default: false },
  defaultPage: { type: Types.Relationship, ref: 'Page' },
  description: { type: Types.Html, wysiwyg: true, height: 150, hint: 'optional description' }
});

1 个答案:

答案 0 :(得分:0)

从看起来,你的模型可能会有很多mainNavigationSections。您必须在当前Page上迭代其中的每一个,并找到相关的SubSections。您需要使用async Node module来运行所有查询并从每个查询中获取结果。

var async  = require('async');
var pID    = req.params.pid; // Or however you are identifying the current page
keystone.list('Page').model.findOne({page: pID}).exec(function (err, page) {
    if (page && !err) {
        async.each(page.mainNavigationSection, function (curMainNavigationSection, cb) {
            keystone.list('SubSection').model
            .find({mainNavigationSection: curMainNavigationSection._id.toString()})
            .exec(function (err2, curSubSections) {
                if (curSubSections.length !== 0 && !err2) {
                    // Do what you need to do with the navigation subSections here
                    // I recommend using a local variable, which will persist through
                    // every iteration of this loop and into the callback function in order
                    // to persist data
                    return cb(null)
                }
                else {
                    return cb(err || "An unexpected error occurred.");
                }
            });
       }, function (err) {
           if (!err) {
               return next(); // Or do whatever
           }
           else {
               // Handle error 
           }
       });
    }
    else {
       // There were no pages or you have an error loading them
    }
});