在mongoDB中按虚拟字段排序(猫鼬)
问题描述:
比方说,我有一些架构,其中有一个像这样的虚拟字段
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...
答
您将无法按虚拟字段进行排序,因为它们没有存储到数据库中.
You won't be able to sort by a virtual field because they are not stored to the database.
虚拟属性是方便携带的属性 但这并不能持续到mongodb.
Virtual attributes are attributes that are convenient to have around but that do not get persisted to mongodb.