samedi 28 février 2015

Sorting Mongoose populate() with a condition

I’m currently using populate() like so:


Schemas:



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


Page rendering:



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


This means that sections.definitions are sorted alphabetically for every section.


I was wondering whether it was possible to pass a condition to the sort within populate, so that I can change the sorting based on the value of (the parent document) section.alpha.


I figured it would look like this:



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

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


Any help would be much appreciated.


Thanks, Samuel


Aucun commentaire:

Enregistrer un commentaire