Skip to content

Commit

Permalink
Merge pull request #14676 from Automattic/vkarpov15/gh-14675
Browse files Browse the repository at this point in the history
fix(query): cast $pull using embedded discriminator schema when discriminator key is set in filter
  • Loading branch information
vkarpov15 authored Jun 21, 2024
2 parents 5b83806 + c639716 commit 3ad5b4f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/helpers/query/castUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
// an update.
if (op === '$pull') {
schematype = schema._getSchema(prefix + key);
if (schematype == null) {
const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options);
if (_res.schematype != null) {
schematype = _res.schematype;
}
}
if (schematype != null && schematype.schema != null) {
obj[key] = cast(schematype.schema, obj[key], options, context);
hasKeys = true;
Expand Down
31 changes: 31 additions & 0 deletions test/model.updateOne.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3017,6 +3017,37 @@ describe('model: updateOne: ', function() {
const doc = await Test.findById(_id);
assert.equal(doc.subdoc['1'], 'foobar');
});
it('handles embedded discriminators with $pull when discriminator key set in filter (gh-14675)', async function() {
const LoginSchema = new Schema({}, { discriminatorKey: 'type', _id: false });
const UserSchema = new Schema({
name: String,
login: LoginSchema
});
UserSchema.path('login').discriminator('ssh-key', new Schema({
keys: {
type: [{
id: { type: String, required: true },
publicKey: { type: String, required: true }
}],
default: []
}
}, { _id: false }));
const User = db.model('Test', UserSchema);

const { _id } = await User.create({
login: {
type: 'ssh-key',
keys: [{ id: 'my-key', publicKey: 'test' }, { id: 'test2', publicKey: 'foo' }]
}
});
const doc = await User.findOneAndUpdate(
{ _id, 'login.type': 'ssh-key' },
{ $pull: { 'login.keys': { id: 'my-key' } } },
{ new: true }
).exec();
assert.equal(doc.login.keys.length, 1);
assert.equal(doc.login.keys[0].id, 'test2');
});
});

async function delay(ms) {
Expand Down

0 comments on commit 3ad5b4f

Please sign in to comment.