Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose subschema array virtuals

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.

like image 277
cyberwombat Avatar asked Oct 12 '14 18:10

cyberwombat


1 Answers

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]
  }
});
like image 167
cyberwombat Avatar answered Nov 15 '22 12:11

cyberwombat