Skip to content

Commit

Permalink
add test coverage and docs re: bulkSave() handling validation errors
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Aug 28, 2024
1 parent 8ce32c0 commit b42be65
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3371,8 +3371,9 @@ Model.bulkWrite = async function bulkWrite(ops, options) {
*
* `bulkSave()` throws errors under the following conditions:
*
* - one of the provided documents fails validation. In this case, `bulkSave()` does not send a `bulkWrite()`, and throws the first validation error.
* - `bulkWrite()` fails (for example, due to being unable to connect to MongoDB or due to duplicate key error)
* - `bulkWrite()` did not insert or update any documents
* - `bulkWrite()` did not insert or update any documents. In this case, `bulkSave()` will throw a DocumentNotFound error.
*
* Note that `bulkSave()` will **not** throw an error if only some of the `save()` calls succeeded.
*
Expand Down
19 changes: 18 additions & 1 deletion test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6939,7 +6939,7 @@ describe('Model', function() {
assert.ok(err == null);

});
it('should error if no documents were inserted (gh-14763)', async function() {
it('should error if no documents were inserted or updated (gh-14763)', async function() {
const fooSchema = new mongoose.Schema({
bar: { type: Number }
}, { optimisticConcurrency: true });
Expand All @@ -6964,6 +6964,23 @@ describe('Model', function() {
assert.equal(err.numAffected, 1);
assert.ok(Array.isArray(err.filter));
});
it('should error if there is a validation error', async function() {
const fooSchema = new mongoose.Schema({
bar: { type: Number }
}, { optimisticConcurrency: true });
const TestModel = db.model('Test', fooSchema);

const docs = [
new TestModel({ bar: 42 }),
new TestModel({ bar: 'taco' })
];
const err = await TestModel.bulkSave(docs).then(() => null, err => err);
assert.equal(err.name, 'ValidationError');

// bulkSave() does not save any documents if any documents fail validation
const fromDb = await TestModel.find();
assert.equal(fromDb.length, 0);
});
it('Using bulkSave should not trigger an error (gh-11071)', async function() {

const pairSchema = mongoose.Schema({
Expand Down

0 comments on commit b42be65

Please sign in to comment.