diff --git a/test/index.test.js b/test/index.test.js index 3063509..989cda1 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -788,4 +788,41 @@ describe('Discriminators work', () => { assert.equal(doc.child.child.fullName, 'Ben Skywalker'); }); }); + + it('can access parent virtuals from child subdocument (gh-64)', async function() { + const childSchema = new mongoose.Schema({ firstName: String }); + childSchema.virtual('uri').get(function() { + // This `uri` virtual is in a subdocument, so in order to get the + // parent's `uri` you need to use this plugin's `parent()` function. + + const parent = this instanceof mongoose.Document + ? this.parent() + : mongooseLeanVirtuals.parent(this) + ; + return `${parent.uri}/child/gh-64-child`; + }); + + const parentSchema = new mongoose.Schema({ + child: childSchema + }); + parentSchema.virtual('uri').get(function() { + return `/parent/gh-64-parent`; + }); + + parentSchema.plugin(mongooseLeanVirtuals); + + const Parent = mongoose.model('gh64', parentSchema); + + const doc = { child: {} }; + + await Parent.create(doc); + + let result = await Parent + .findOne() + .lean({ virtuals: true }); + assert.equal( + result.child.uri, + '/parent/gh-64-parent/child/gh-64-child' + ); + }); });