2012-07-22 63 views
3

我有这个模式猫鼬 - 排序数组长度

var PostSchema = new Schema({ 
    title: {type: String, trim: true} 
    , description: {type: String, trim: true} 
    , votes: [{ type: Schema.ObjectId, ref: 'User' }] 
}) 

我想基于票数即职位排序,我需要通过数组的长度进行排序。

试图以通常的方式,但din't工作

PostSchema.statics.trending = function (cb) { 
    return this.find().sort('votes', -1).limit(5).exec(cb) 
} 

任何帮助吗?

版猫鼬我使用的是2.7.2

回答

7

你不能直接这样做。为了能够对数组长度进行排序,您必须将其保存在一个单独的字段(votes_count,或其他)中,并在您向/从votes推/拉元素时更新它。

然后你排序在votes_count字段。如果您也将其编入索引,查询速度会更快。