mongoosesubschema数组虚拟

我发布这个问题和答案,希望它会帮助别人(或者如果有更好的答案)。

如何以数组forms为Mongoose嵌套模式创build虚拟?

这里是模式:

var Variation = new Schema({ label: { type: String } }); var Product = new Schema({ title: { type: String } variations: { type: [Variation] } }); 

我想如何虚拟variations 。 看来,如果子文档不是一个数组,那么我们可以简单地做到这一点:

 Product.virtual('variations.name')... 

但是,这只适用于非数组。

关键是将虚拟定义为子模式的一部分,而不是父级,并且必须在子模式被分配给父级之前完成。 访问父对象可以通过this.parent()

 var Variation = new Schema({ label: { type: String } }); // Virtual must be defined before the subschema is assigned to parent schema Variation.virtual("name").get(function() { // Parent is accessible var parent = this.parent(); return parent.title + ' ' + this.label; }); var Product = new Schema({ title: { type: String } variations: { type: [Variation] } });