I am posting this question and the answer in hopes it will help someone else (or if there's a better answer).
How to I create virtuals for Mongoose nested schemas when in array form?
Here are the schemas:
var Variation = new Schema({
label: {
type: String
}
});
var Product = new Schema({
title: {
type: String
}
variations: {
type: [Variation]
}
});
How I would like a virtual on variations
. It seems that if the sub doc is not an array then we can simply do this:
Product.virtual('variations.name')...
But that only works for non arrays.
The key is to define the virtual as part of the subschema rather than parent and it must be done before the subschema is assigned to parent. Access to the parent object can be done via 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]
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With