Skip to content

Commit

Permalink
fix: better way to handle non-MongoBulkWriteErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Oct 29, 2024
1 parent 63525bb commit 66b44b5
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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) {
Expand All @@ -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();
});
Expand Down

0 comments on commit 66b44b5

Please sign in to comment.