2012-07-22 78 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字段。如果您也將其編入索引,查詢速度會更快。