Skip to content

Commit

Permalink
fix(schema): make creating top-level virtual underneath subdocument e…
Browse files Browse the repository at this point in the history
…quivalent to creating virtual on the subdocument

Fix #13189
Re: #8210
Re: #8198
  • Loading branch information
vkarpov15 committed Mar 22, 2023
1 parent 14112d6 commit 9370452
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
2 changes: 1 addition & 1 deletion lib/schema.js
Expand Up @@ -2217,7 +2217,7 @@ Schema.prototype.virtual = function(name, options) {
}

// Workaround for gh-8198: if virtual is under document array, make a fake
// virtual. See gh-8210
// virtual. See gh-8210, gh-13189
const parts = name.split('.');
let cur = parts[0];
for (let i = 0; i < parts.length - 1; ++i) {
Expand Down
28 changes: 24 additions & 4 deletions test/model.populate.test.js
Expand Up @@ -7934,31 +7934,51 @@ describe('model: populate:', function() {
assert.equal(res.nested.events[0].nestedLayer.users_$[0].name, 'test');
});

it('accessing populate virtual prop (gh-8198)', async function() {
it('accessing populate virtual prop (gh-13189) (gh-8198)', async function() {
const FooSchema = new Schema({
name: String,
children: [{
barId: { type: Schema.Types.ObjectId, ref: 'Test' },
quantity: Number
}]
}],
child: {
barId: {
type: 'ObjectId',
ref: 'Test'
}
}
});
FooSchema.virtual('children.bar', {
ref: 'Test',
localField: 'children.barId',
foreignField: '_id',
justOne: true
});
FooSchema.virtual('child.bar', {
ref: 'Test',
localField: 'child.barId',
foreignField: '_id',
justOne: true
});
const BarSchema = Schema({ name: String });
const Foo = db.model('Test1', FooSchema);
const Bar = db.model('Test', BarSchema);

const bar = await Bar.create({ name: 'bar' });
const foo = await Foo.create({
name: 'foo',
children: [{ barId: bar._id, quantity: 1 }]
children: [{ barId: bar._id, quantity: 1 }],
child: {
barId: bar._id
}
});
const foo2 = await Foo.findById(foo._id).populate('children.bar');
const foo2 = await Foo.findById(foo._id).populate('children.bar child.bar');
assert.equal(foo2.children[0].bar.name, 'bar');
assert.equal(foo2.child.bar.name, 'bar');

const asObject = foo2.toObject({ virtuals: true });
assert.equal(asObject.children[0].bar.name, 'bar');
assert.equal(asObject.child.bar.name, 'bar');
});

describe('gh-8247', function() {
Expand Down

0 comments on commit 9370452

Please sign in to comment.