Skip to content

Commit

Permalink
Merge pull request #15036 from Automattic/vkarpov15/gh-14978
Browse files Browse the repository at this point in the history
fix(model): handle array filters when casting bulkWrite
  • Loading branch information
vkarpov15 authored Nov 13, 2024
2 parents 8799da2 + c9cbea0 commit 7aba322
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/helpers/model/castBulkWrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ module.exports = function castBulkWrite(originalModel, op, options) {
});
op['updateOne']['update'] = castUpdate(model.schema, update, {
strict: strict,
upsert: op['updateOne'].upsert
upsert: op['updateOne'].upsert,
arrayFilters: op['updateOne'].arrayFilters
}, model, op['updateOne']['filter']);
} catch (error) {
return callback(error, null);
Expand Down Expand Up @@ -162,7 +163,8 @@ module.exports = function castBulkWrite(originalModel, op, options) {

op['updateMany']['update'] = castUpdate(model.schema, op['updateMany']['update'], {
strict: strict,
upsert: op['updateMany'].upsert
upsert: op['updateMany'].upsert,
arrayFilters: op['updateMany'].arrayFilters
}, model, op['updateMany']['filter']);
} catch (error) {
return callback(error, null);
Expand Down
49 changes: 49 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4125,6 +4125,55 @@ describe('Model', function() {
assert.equal(err.validationErrors[0].errors['num'].name, 'CastError');
});

it('handles array filters (gh-14978)', async function() {
const embedDiscriminatorSchema = new mongoose.Schema({
field1: String
});

const embedSchema = new mongoose.Schema({
field: String,
key: String
}, { discriminatorKey: 'key' });
embedSchema.discriminator('Type1', embedDiscriminatorSchema);

const testSchema = new mongoose.Schema({
testArray: [embedSchema]
});
const TestModel = db.model('Test', testSchema);

const test = new TestModel({
testArray: [{
key: 'Type1',
field: 'field',
field1: 'field1'
}]
});
const r1 = await test.save();
assert.equal(r1.testArray[0].field1, 'field1');

const field1update = 'field1 update';
await TestModel.bulkWrite([{
updateOne: {
filter: { _id: r1._id },
update: {
$set: {
'testArray.$[element].field1': field1update,
'testArray.$[element].nonexistentProp': field1update
}
},
arrayFilters: [
{
'element._id': r1.testArray[0]._id,
'element.key': 'Type1'
}
]
}
}]);
const r2 = await TestModel.findById(r1._id).lean();
assert.equal(r2.testArray[0].field1, field1update);
assert.strictEqual(r2.testArray[0].nonexistentProp, undefined);
});

it('with child timestamps and array filters (gh-7032)', async function() {
const childSchema = new Schema({ name: String }, { timestamps: true });

Expand Down

0 comments on commit 7aba322

Please sign in to comment.