Skip to content

Commit

Permalink
Merge pull request #6501 from lineus/fix-6487
Browse files Browse the repository at this point in the history
fixes #6487 - fix getVirtual, set $nestedSchemaPath to full value of nestedSchemaPath
  • Loading branch information
vkarpov15 authored May 23, 2018
2 parents 048aabf + 26e48e6 commit 782d4a8
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/services/populate/getVirtual.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function getVirtual(schema, name) {
let _cur = parts[i + 1];
if (discriminatorSchema.virtuals[_cur]) {
discriminatorSchema.virtuals[_cur].$nestedSchemaPath =
(nestedSchemaPath.length > 0 ? '.' : '') + cur;
(nestedSchemaPath.length > 0 ? nestedSchemaPath + '.' : '') + cur;
return discriminatorSchema.virtuals[_cur];
}
}
Expand Down
60 changes: 60 additions & 0 deletions test/model.populate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6472,6 +6472,66 @@ describe('model: populate:', function() {
assert.strictEqual(doc.o[0].a.name, 'testing');
});
});

it('handles embedded discriminator (gh-6487)', function() {
const userSchema = new Schema({ employeeId: Number, name: String });
const UserModel = db.model('gh6487Users', userSchema);

const eventSchema = new Schema(
{ message: String },
{ discriminatorKey: 'kind' }
);

const batchSchema = new Schema({
nested: new Schema({
events: [eventSchema]
})
});

const docArray = batchSchema.path('nested.events');

const clickedSchema = new Schema({
element: { type: String },
users: [Number]
},{
toJSON: { virtuals: true },
toObject: { virtuals: true }
});

clickedSchema.virtual('users_$', {
ref: 'gh6487Users',
localField: 'users',
foreignField: 'employeeId'
});

docArray.discriminator('Clicked', clickedSchema);

docArray.discriminator('Purchased', new Schema({
product: { type: String }
}));

const Batch = db.model('gh6487EventBatch', batchSchema);

const user = { employeeId: 1, name: 'Test name' };
const batch = {
nested: {
events: [
{ kind: 'Clicked', element: '#hero', message: 'hello', users: [1] },
{ kind: 'Purchased', product: 'action-figure-1', message: 'world' }
]
}
};

return co(function*() {
yield UserModel.create(user);
yield Batch.create(batch);
let docs = yield Batch.find({})
.populate('nested.events.users_$')
.lean();
let name = docs[0].nested.events[0].users_$[0].name;
assert.strictEqual(name, 'Test name');
});
});
});
});
});

0 comments on commit 782d4a8

Please sign in to comment.