使用条件对Mongoose populate()进行排序

时间:2015-02-28 14:33:01

标签: node.js mongodb mongoose

我目前正在使用populate(),如此:

架构:

  var DefinitionSchema = mongoose.Schema({
    title: String, 
    slug: String, 
    description: String
  });
  DefinitionSchema.index({description: 'text'});
  DefinitionSchema.plugin(textSearch);

  var SectionSchema = mongoose.Schema({
      heading: String,
      intro: String,
      alpha: false,
      definitions: [{ type: Schema.Types.ObjectId, ref: 'Definition' }]
  });

  var PageSchema = mongoose.Schema({
    time : { type : Date, default: Date.now },
    title: String, 
    slug: String, 
    intro: String,
    body: String,  
    sections: [SectionSchema]
  });

页面渲染:

exports.edit = function(req, res){
    Page.findOne({ slug: req.param('page') }, function(err, page){
        res.render('admin/page_edit', { page: page});
    })
    .populate({path: 'sections.definitions', options: {sort: {slug: 'asc'}}});
};

这意味着sections.definitions按字母顺序排列每个部分。

我想知道是否可以将条件传递给sort中的populate,以便我可以根据(父文档)section.alpha的值更改排序

我认为它看起来像这样:

function sorting(section) {
    var sort = {}
    if (section.alpha) {
        sort = {slug: 'ace'}
    }
    return sort;
}

query
...
.populate({path: 'sections.definitions', options: {sort: sorting(sections)}});

非常感谢任何帮助。

谢谢, 塞缪尔

1 个答案:

答案 0 :(得分:0)

通过将res.render移至exec函数并在此时执行sort来找到解决方案:

exports.edit = function(req, res){
    Page.findOne({ slug: req.param('page') })
    .populate({path: 'sections.definitions'}).exec(function(err, page){
        page.sections.forEach(function(section) {           
            if (section.alpha) {
                section.definitions.sort({title: 'asc'});   
            }
        })
        res.render('admin/page_edit', { page: page});
    })
};