From 6c1dcb28cc6eb528a3710f64fe3cc95ea7e628ff Mon Sep 17 00:00:00 2001 From: Hafez Date: Wed, 13 Nov 2019 15:50:42 +0200 Subject: [PATCH 1/2] Fixes #8331 --- lib/helpers/model/castBulkWrite.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/helpers/model/castBulkWrite.js b/lib/helpers/model/castBulkWrite.js index f4e15648979..f724afb0b31 100644 --- a/lib/helpers/model/castBulkWrite.js +++ b/lib/helpers/model/castBulkWrite.js @@ -34,6 +34,9 @@ module.exports = function castBulkWrite(model, op, options) { op = op['updateOne']; return (callback) => { try { + if (!op['filter']) throw new Error('Must provide a filter object.'); + if (!op['update']) throw new Error('Must provide an update object.'); + op['filter'] = cast(model.schema, op['filter']); op['update'] = castUpdate(model.schema, op['update'], { strict: model.schema.options.strict, @@ -61,6 +64,9 @@ module.exports = function castBulkWrite(model, op, options) { op = op['updateMany']; return (callback) => { try { + if (!op['filter']) throw new Error('Must provide a filter object.'); + if (!op['update']) throw new Error('Must provide an update object.'); + op['filter'] = cast(model.schema, op['filter']); op['update'] = castUpdate(model.schema, op['update'], { strict: model.schema.options.strict, From a91dc93a3750d024899ac8b3a56a9d2b8f682759 Mon Sep 17 00:00:00 2001 From: Hafez Date: Wed, 13 Nov 2019 16:04:54 +0200 Subject: [PATCH 2/2] Add test for #8331 --- test/model.test.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/test/model.test.js b/test/model.test.js index a0bf8dc8960..ce2ceddb56e 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -5671,6 +5671,34 @@ describe('Model', function() { then(() => Model.findOne()). then(doc => assert.equal(doc.nested.name, 'foo')); }); + + it('throws an error if no update object is provided (gh-8331)', function() { + const userSchema = new Schema({ name: { type: String, required: true } }); + const User = db.model('gh8331', userSchema); + + return co(function*() { + const createdUser = yield User.create({ name: 'Hafez' }); + let threw = false; + try { + yield User.bulkWrite([{ + updateOne: { + filter: { _id: createdUser._id } + } + }]); + } + catch (err) { + threw = true; + assert.equal(err.message, 'Must provide an update object.'); + } + finally { + assert.equal(threw, true); + + const userAfterUpdate = yield User.findOne({ _id: createdUser._id }); + + assert.equal(userAfterUpdate.name, 'Hafez', 'Document data is not wiped if no update object is provided.'); + } + }); + }); }); it('insertMany with Decimal (gh-5190)', function(done) {