Skip to content

Commit

Permalink
add test case for #64
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jun 7, 2024
1 parent 8fcdc13 commit 7f06420
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
);
});
});

0 comments on commit 7f06420

Please sign in to comment.