mongoose - sort by array length
mongodb, mongoose, sorting
Solution
You can't do that directly. To be able to sort on array length, you have to maintain it in a separate field (`votes_count`, or whatever) and update it when you push/pull elements to/from `votes`.
Then you sort on that `votes_count` field. If you also index it, queries will be faster.
Problem
I am having this schema ``` var PostSchema = new Schema({ title: {type: String, trim: true} , description: {type: String, trim: true} , votes: [{ type: Schema.ObjectId, ref: 'User' }] }) ``` I want to sort posts based on votes i.e, I need to sort by array length. Tried the usual way, but din't work ``` PostSchema.statics.trending = function (cb) { return this.find().sort('votes', -1).limit(5).exec(cb) } ``` Any help? version of mongoose I am using is 2.7.2