我发布了这个问题和答案,希望它能帮助其他人(或者如果有更好的答案)。
如何在数组形式时为 Mongoose 嵌套模式创建虚拟?
这是模式:
var Variation = new Schema({
label: {
type: String
}
});
var Product = new Schema({
title: {
type: String
}
variations: {
type: [Variation]
}
});
我如何想要一个虚拟的变体
。似乎如果子文档不是数组,那么我们可以简单地这样做:
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]
}
});
关于node.js - Mongoose 子模式数组虚拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328481/