在mongoDB中使用虚拟字段sorting(mongoose)

比方说,我有一些像这样的虚拟领域的架构

var schema = new mongoose.Schema( { name: { type: String } }, { toObject: { virtuals: true }, toJSON: { virtuals: true } }); schema.virtual("name_length").get(function(){ return this.name.length; }); 

在查询中可以通过虚拟字段对结果进行sorting? 就像是

 schema.find().sort("name_length").limit(5).exec(function(docs){ ... }); 

当我尝试这个,结果很简单,没有sorting…

您将无法通过虚拟字段sorting,因为它们不存储到数据库。

虚拟属性是方便的属性,但是不会持久保存到mongodb中。

http://mongoosejs.com/docs/2.7.x/docs/virtuals.html