Skip to content

Commit f386004

Browse files
committed
fix(model): handle array filters when casting bulkWrite
Fix #14978
1 parent a0fdb9e commit f386004

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

lib/helpers/model/castBulkWrite.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,8 @@ module.exports = function castBulkWrite(originalModel, op, options) {
103103
});
104104
op['updateOne']['update'] = castUpdate(model.schema, update, {
105105
strict: strict,
106-
upsert: op['updateOne'].upsert
106+
upsert: op['updateOne'].upsert,
107+
arrayFilters: op['updateOne'].arrayFilters
107108
}, model, op['updateOne']['filter']);
108109
} catch (error) {
109110
return callback(error, null);
@@ -162,7 +163,8 @@ module.exports = function castBulkWrite(originalModel, op, options) {
162163

163164
op['updateMany']['update'] = castUpdate(model.schema, op['updateMany']['update'], {
164165
strict: strict,
165-
upsert: op['updateMany'].upsert
166+
upsert: op['updateMany'].upsert,
167+
arrayFilters: op['updateMany'].arrayFilters
166168
}, model, op['updateMany']['filter']);
167169
} catch (error) {
168170
return callback(error, null);

test/model.test.js

+48
Original file line numberDiff line numberDiff line change
@@ -4125,6 +4125,54 @@ describe('Model', function() {
41254125
assert.equal(err.validationErrors[0].errors['num'].name, 'CastError');
41264126
});
41274127

4128+
it('handles array filters (gh-14978)', async function() {
4129+
const embedDiscriminatorSchema = new mongoose.Schema({
4130+
field1: String
4131+
});
4132+
4133+
const embedSchema = new mongoose.Schema({
4134+
field: String,
4135+
key: String
4136+
}, { discriminatorKey: 'key' });
4137+
embedSchema.discriminator('Type1', embedDiscriminatorSchema);
4138+
4139+
const testSchema = new mongoose.Schema({
4140+
testArray: [embedSchema]
4141+
});
4142+
const TestModel = db.model('Test', testSchema);
4143+
4144+
const test = new TestModel({
4145+
testArray: [{
4146+
key: 'Type1',
4147+
field: 'field',
4148+
field1: 'field1'
4149+
}]
4150+
});
4151+
const r1 = await test.save();
4152+
assert.equal(r1.testArray[0].field1, 'field1');
4153+
4154+
const field1update = 'field1 update';
4155+
await TestModel.bulkWrite([{
4156+
updateOne: {
4157+
filter: { _id: r1._id },
4158+
update: {
4159+
$set: {
4160+
'testArray.$[element].field1': field1update
4161+
}
4162+
},
4163+
arrayFilters: [
4164+
{
4165+
'element._id': r1.testArray[0]._id,
4166+
'element.key': 'Type1'
4167+
}
4168+
]
4169+
}
4170+
}]);
4171+
const r2 = await TestModel.findById(r1._id);
4172+
assert.equal(r2.testArray[0].field1, field1update);
4173+
4174+
});
4175+
41284176
it('with child timestamps and array filters (gh-7032)', async function() {
41294177
const childSchema = new Schema({ name: String }, { timestamps: true });
41304178

0 commit comments

Comments
 (0)