Sorting by virtual field in mongoDB (mongoose)

2019-01-15 14:28发布

问题:

Let's say I have some Schema which has a virtual field like this

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

schema.virtual("name_length").get(function(){
    return this.name.length;
});

In a query is it possible to sort the results by the virtual field? Something like

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

When I try this, the results are simple not sorted...

回答1:

You won't be able to sort by a virtual field because they are not stored to the database.

Virtual attributes are attributes that are convenient to have around but that do not get persisted to mongodb.

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