Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add test coverage and docs re: bulkSave() handling validation errors
  • Loading branch information
vkarpov15 committed Aug 28, 2024
commit b42be657de04b9ad2eb1b13fe74c67aee9a71448
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