Mongoose: Support for nested virtuals, virtuals in subdocuments

Created on 12 Feb 2011  ·  6Comments  ·  Source: Automattic/mongoose

var Page = new Schema({
    author: {
        first_name: String
      , last_name: String
    }
});
Page.virtual("author.full_name").get(function() {
    return this.author.first_name + " " + this.author.last_name;
});

// Later
myPage = new Page({author: {first_name: "John", last_name: "Doe"}});
myPage.author.full_name; // == undefined
myPage.get("author.full_name"); // == "John Doe"

I haven't tried making a new schema for the author with its own virtuals. Maybe that would work, but according to other issue reports, sub-schemas work optimally in arrays a.t.m., not as plain subdocuments.

Looking at the source, this doesn't look to be impossible, just missing some clever split(".") logic while adding the virtual to the schema tree.

The get method works fine for the time being, but the other syntax would be preferrable. :)

Most helpful comment

The solution above works, but you'll also need to set virtuals on for the nested schema:

Variation.set('toJSON', {
    virtuals: true
});

All 6 comments

Ofcourse this fix should also be applied to methods on subdocuments

What if author is an array? can we do a virtual on each of this array?

+1 support for arrays

+100 support for arrays

Figured it out:.

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]
  }
});

The solution above works, but you'll also need to set virtuals on for the nested schema:

Variation.set('toJSON', {
    virtuals: true
});
Was this page helpful?
0 / 5 - 0 ratings