diff --git a/lib/model.js b/lib/model.js index 9807c43387..1d3dd8f071 100644 --- a/lib/model.js +++ b/lib/model.js @@ -10,6 +10,7 @@ const Document = require('./document'); const DocumentNotFoundError = require('./error/notFound'); const EventEmitter = require('events').EventEmitter; const Kareem = require('kareem'); +const { MongoBulkWriteError } = require('mongodb'); const MongooseBulkWriteError = require('./error/bulkWriteError'); const MongooseError = require('./error/index'); const ObjectParameterError = require('./error/objectParameter'); @@ -3417,6 +3418,11 @@ Model.bulkSave = async function bulkSave(documents, options) { (err) => ({ bulkWriteResult: null, bulkWriteError: err }) ); + // If not a MongoBulkWriteError, treat this as all documents failed to save. + if (bulkWriteError != null && !(bulkWriteError instanceof MongoBulkWriteError)) { + throw bulkWriteError; + } + const matchedCount = bulkWriteResult?.matchedCount ?? 0; const insertedCount = bulkWriteResult?.insertedCount ?? 0; if (writeOperations.length > 0 && matchedCount + insertedCount < writeOperations.length && !bulkWriteError) { @@ -3430,13 +3436,7 @@ Model.bulkSave = async function bulkSave(documents, options) { const successfulDocuments = []; for (let i = 0; i < documents.length; i++) { const document = documents[i]; - const hasWriteErrors = bulkWriteError && Array.isArray(bulkWriteError.writeErrors); - // If there is an error, but the error doesn't have a list of `writeErrors`, then treat the error as - // indicating that all documents failed. This might happen because of a MongooseServerSelectionError. - if (!hasWriteErrors) { - continue; - } - const documentError = bulkWriteError.writeErrors.find(writeError => { + const documentError = bulkWriteError && bulkWriteError.writeErrors.find(writeError => { const writeErrorDocumentId = writeError.err.op._id || writeError.err.op.q._id; return writeErrorDocumentId.toString() === document._doc._id.toString(); });