Virtual virtual arrays subsphema mongoose

I am posting this question and answer in the hope that it will help someone else (or if there is a better answer).

How to create virtual objects for nested Mongoose schemas in array form?

Here are the diagrams:

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

As I would like virtual on variations . It seems that if the sub doc is not an array, we can simply do this:

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

But this only works for non-arrays.

+5
source share
1 answer

The key is to define the virtual part as part of the subcircuit, not the parent, and it must be executed before the subcircuit is assigned to the parent. Access to the parent object is possible through 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] } }); 
+4
source

Source: https://habr.com/ru/post/1204519/


All Articles