6

I have a couple Schemas:

var parentSchema = new Schema({name: String});
var childSchema = new Schema({
    name: String,
    parent: {type: Schema.ObjectId, ref: 'Parent'}
});

I want to be able to call Child.find().populate('parent') and then use the following virtual getter:

childSchema.virtual('url').get(function () {
    return "/" + this.parent.name + "/" + this.name
});

However, when I call the find().populate() and then pass the resulting child to my view, and attempt to use child.url, I always get parent.name set to undefined. What am I doing wrong?

hickninja
  • 61
  • 1

1 Answers1

0

I know it's an old question but you can try something like:

childSchema.virtual('url').get(function () {
    this.populate("parent");
    return "/" + this.parent.name + "/" + this.name
});

It's mentioned here in the official documentation.

Freezystem
  • 4,494
  • 1
  • 32
  • 35