Skip to content

Commit

Permalink
fix(document): make validateUpdatedOnly option handle pre-existing …
Browse files Browse the repository at this point in the history
…errors

Fix #8091
  • Loading branch information
vkarpov15 committed Aug 24, 2019
1 parent b0fd1b0 commit c8aaa01
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -2075,8 +2075,22 @@ Document.prototype.$__validate = function(options, callback) {

const _this = this;
const _complete = () => {
const err = this.$__.validationError;
let err = this.$__.validationError;
this.$__.validationError = undefined;

if (shouldValidateModifiedOnly && err != null) {
// Remove any validation errors that aren't from modified paths
const errors = Object.keys(err.errors);
for (const errPath of errors) {
if (!this.isModified(errPath)) {
delete err.errors[errPath];
}
}
if (Object.keys(err.errors).length === 0) {
err = void 0;
}
}

this.$__.cachedRequired = {};
this.emit('validate', _this);
this.constructor.emit('validate', _this);
Expand Down
18 changes: 18 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2351,6 +2351,24 @@ describe('document', function() {
});
});

it('validateModifiedOnly with pre existing validation error (gh-8091)', function() {
const schema = mongoose.Schema({
title: String,
coverId: Number
}, { validateModifiedOnly: true });

const Model = db.model('gh8091', schema);

return co(function*() {
yield Model.collection.insertOne({ title: 'foo', coverId: parseFloat('not a number') });

const doc = yield Model.findOne();
doc.title = 'bar';
// Should not throw
yield doc.save();
});
});

it('handles non-errors', function(done) {
const schema = new Schema({
name: { type: String, required: true }
Expand Down

0 comments on commit c8aaa01

Please sign in to comment.