猫鼬瘦查询,虚拟不显示 [英] mongoose lean query, virtuals not showing
问题描述
我在猫鼬(我使用版本3.6.17)上设置了以下架构:
I have the following schema set up on mongoose, Im using version 3.6.17:
var PostSchema = new Schema({
_id: { type: String, required: true, index: { unique: true } },
video: { type: String, default: ''},
cover: { type: String, default: ''},
createdAt: { type: Date, default: Date.now },
lastUpdate: { type: Date, default: Date.now }
}, { autoIndex: true, toObject: { virtuals: true }, toJSON: { virtuals: true } });
以及以下虚拟机:
PostSchema.virtual('replied').get(function () {
return false;
});
PostSchema.virtual('cover_url').get(function () {
return config.cover.server + this.cover;
});
PostSchema.virtual('video_url').get(function () {
return config.video.server + this.video;
});
当我执行汇总查询时:
Post.aggregate( { $match: { replyTo: { $ne: "" }, author: user._id, draft: false } },
{ $project: {
_id: 1,
video: 1,
video_url: 1,
cover: 1,
cover_url: 1,
createdAt: 1,
lastUpdate: 1,
Ireplied : { $not: "$replied"} }
}, function ( ) ....
此时虚拟机返回,但它们返回的属性为this.cover或this.video未定义.
At this point the virtuals return but they return with the attribute this.cover or this.video undefined.
当我执行Post.findOne(..).lean().populate(...)等时,我根本不获得虚拟,也不使用Post.find().lean().populate (...)
And when I do a Post.findOne(..).lean().populate(...) etc, I dont get the virtuals at all, neither with a Post.find().lean().populate(...)
我是否缺少Post架构上的某些内容,以便能够返回虚拟对象,还是我做错了什么? 为什么通过聚合操作虚拟机返回未定义的值"this.cover"?
Am I missing something on the Post schema, to be able to return the virtuals, or am I doing something wrong? And why with the aggregate operation the virtuals return the value "this.cover" as undefined?
谢谢!
推荐答案
lean
查询返回原始的MongoDB
驱动程序响应作为普通的js
对象.因此,其中没有getters
,setters
,virtuals
或其他猫鼬魔法".有关更多信息,请参见 Api文档.
lean
queries return raw MongoDB
driver response as a plain js
object. So, there are no getters
, setters
, virtuals
or other "Mongoose magic" in it. See Api docs for more info.
lean
查询的目的是尽可能快地返回对象.如果需要virtuals
-使用普通的Mongoose查询.
The point of lean
queries is to return your objects as fast as possible. If you need virtuals
- use ordinary Mongoose queries.
对于聚合,它是100%MongoDB
功能,Mongoose无法控制它.因此,当您从Mongoose调用aggregate
时,其作用与MongoDB
控制台中的aggregate
相同. aggregate
无法与虚拟机一起使用,因为您的数据库中没有此类字段.猫鼬甚至都无法根据您的架构(如对findOneAndUpdate
参数所做的那样)对聚合查询进行转换,因为聚合会在每个步骤更改文档的形状.请参见 Mongoose API文档和
As for aggregation, it's 100% MongoDB
feature and Mongoose can't control it. So, when you calling aggregate
from Mongoose it works the same as aggregate
in MongoDB
console. aggregate
can't operate with virtuals, because there are no such fields in your database. Mongoose can't even cast your aggregation query according to your schema (like it's doing with findOneAndUpdate
arguments), because aggregation changes the shape of the document on each step. See Mongoose API Docs and MongoDB Docs for more info.
这篇关于猫鼬瘦查询,虚拟不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!