Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for nested virtuals, virtuals in subdocuments #245

Closed
eirikurn opened this issue Feb 12, 2011 · 6 comments
Closed

Support for nested virtuals, virtuals in subdocuments #245

eirikurn opened this issue Feb 12, 2011 · 6 comments

Comments

@eirikurn
Copy link
Contributor

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. :)

@eirikurn
Copy link
Contributor Author

Ofcourse this fix should also be applied to methods on subdocuments

@mroushdy
Copy link

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

@cyberwombat
Copy link

+1 support for arrays

@dynnamitt
Copy link

+100 support for arrays

@cyberwombat
Copy link

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

@matheusdavidson
Copy link

matheusdavidson commented Mar 5, 2017

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

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

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants