在mongoDB中按虚拟字段排序(mongoose)

ArV*_*Van 9 sorting mongoose mongodb node.js

假设我有一些Schema,它有一个像这样的虚拟字段

var schema = new mongoose.Schema(
{
    name: { type: String }
},
{
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

schema.virtual("name_length").get(function(){
    return this.name.length;
});
Run Code Online (Sandbox Code Playgroud)

在查询中是否可以按虚拟字段对结果进行排序?就像是

schema.find().sort("name_length").limit(5).exec(function(docs){ ... });
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时,结果很简单没有排序......

Ale*_*lex 11

您将无法按虚拟字段排序,因为它们未存储到数据库中.

虚拟属性是便于使用但不会持久保存到mongodb的属性.

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

  • 没错,你也不能在查找中使用它们. (2认同)