Mongoose sort by populated field Mongoose sort by populated field mongoose mongoose

Mongoose sort by populated field


The Mongoose API does seem to support sorting on populated fields, but there's a bug that breaks it entirely: https://github.com/Automattic/mongoose/issues/2202. You get a result, but it's just plain wrong.

For small amounts of data, it's fine to sort the result array using Javascript Array.prototype.sort(). Keep in mind that this directly modifies the sorted array though.

What I've done in this case is add a sort key property to the schema for the model you want to sort. For your example, you could do:

var FollowActionSchema = new Schema({  // ...  'brandSortKey': { type: String },  'brand': {    type: ObjectId,    ref: 'Brand'  },  // ...});

This isn't perfect, because you'll have to explicitly set this property with the correct key yourself:

var FollowAction = Model('FollowAction', FollowActionSchema);var aBrand = // some brand objectvar f = new FollowAction({   brand: aBrand._id,   brandSortKey: aBrand.name   // other properties}); 

But, then you can sort directly via the Mongoose API (or MongoDB):

FollowAction.find({})   .sort({ brandSortKey:1 })   .exec(function (err, sortedResults) {       // do something with sorted results.   });


Get the idea from this simple example

 Post.find({'_id': userId})           .limit(10)           .skip(0)           .sort({'created_at':-1}) // this is used to sort           .exec(function(error, result){            if(!error){              // console.log(result);              res.send({data:result});            } else{              console.log(error);            }        });