diff --git a/lib/helpers/model/castBulkWrite.js b/lib/helpers/model/castBulkWrite.js index 1afb36987f..6420ad7e2e 100644 --- a/lib/helpers/model/castBulkWrite.js +++ b/lib/helpers/model/castBulkWrite.js @@ -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); @@ -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); diff --git a/test/model.test.js b/test/model.test.js index 8584b08a85..5bc1317e52 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -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 });