在 mongoDB (mongoose) 中按虚拟字段排序 [英] Sorting by virtual field in mongoDB (mongoose)

查看:29
本文介绍了在 mongoDB (mongoose) 中按虚拟字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

这篇关于在 mongoDB (mongoose) 中按虚拟字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆