Node.js 使用条件对Mongoose populate()进行排序
我目前正在使用如下方式填充: 模式:Node.js 使用条件对Mongoose populate()进行排序,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我目前正在使用如下方式填充: 模式: var DefinitionSchema = mongoose.Schema({ title: String, slug: String, description: String }); DefinitionSchema.index({description: 'text'}); DefinitionSchema.plugin(textSearch); var SectionSchema = mongoose
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都按字母顺序排序
我想知道是否可以将条件传递给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)}});
任何帮助都将不胜感激
谢谢,
Samuel通过将res.render移动到exec函数中,并在该点执行排序来找到解决方案:
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});
})
};