gpt4 book ai didi

node.js - 按 mongoDB (mongoose) 中的虚拟字段排序

转载 作者:IT老高 更新时间:2023-10-28 23:25:03 27 4
gpt4 key购买 nike

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

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

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

在查询中是否可以按虚拟字段对结果进行排序?类似的东西

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

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

最佳答案

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

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

关于node.js - 按 mongoDB (mongoose) 中的虚拟字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13452795/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com