我在猫鼬上设置了以下架构,我使用的是 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 未定义。
当我做 Post.findOne(..).lean().populate(...) 等时,我根本没有得到虚拟,也没有 Post.find().lean().populate(.. .)
我是否在 Post 模式上遗漏了一些东西,以便能够返回虚拟对象,或者我做错了什么?为什么在聚合操作中虚拟返回值“this.cover”为未定义?
谢谢!