mongoose - 按数组长度排序

Mad*_*han 4 sorting mongoose mongodb

我有这个架构

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

我想根据投票对帖子进行排序,即我需要按数组长度排序.

尝试通常的方式,但不工作

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

有帮助吗?

我使用的猫鼬版本是2.7.2

Ser*_*sev 7

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

然后你在那个votes_count领域排序.如果您也将其编入索引,则查询速度会更快.