diff --git a/lib/model.js b/lib/model.js index cc0ede41af..c3dc7d05d3 100644 --- a/lib/model.js +++ b/lib/model.js @@ -3472,18 +3472,22 @@ Model.bulkWrite = async function bulkWrite(ops, options) { let validOps = []; let validationErrors = []; const results = []; - for (let i = 0; i < validations.length; ++i) { - validations[i]((err) => { - if (err == null) { - validOps.push(i); - } else { - validationErrors.push({ index: i, error: err }); - results[i] = err; - } - if (--remaining <= 0) { - completeUnorderedValidation.call(this); - } - }); + if (remaining === 0) { + completeUnorderedValidation.call(this); + } else { + for (let i = 0; i < validations.length; ++i) { + validations[i]((err) => { + if (err == null) { + validOps.push(i); + } else { + validationErrors.push({ index: i, error: err }); + results[i] = err; + } + if (--remaining <= 0) { + completeUnorderedValidation.call(this); + } + }); + } } validationErrors = validationErrors. diff --git a/test/model.test.js b/test/model.test.js index af1f267cf0..9f2af2e8a2 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -5923,6 +5923,15 @@ describe('Model', function() { }); + it('Model.bulkWrite(...) does not hang with empty array and ordered: false (gh-13664)', async function() { + const userSchema = new Schema({ name: String }); + const User = db.model('User', userSchema); + + const err = await User.bulkWrite([], { ordered: false }).then(() => null, err => err); + assert.ok(err); + assert.equal(err.name, 'MongoInvalidArgumentError'); + }); + it('allows calling `create()` after `bulkWrite()` (gh-9350)', async function() { const schema = Schema({ foo: Boolean }); const Model = db.model('Test', schema);