Skip to content

Commit

Permalink
fix(document): make calling validate() with single nested subpath o…
Browse files Browse the repository at this point in the history
…nly validate that single nested subpath

Fix #8626
  • Loading branch information
vkarpov15 committed Feb 28, 2020
1 parent b1a094f commit 3eee840
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
17 changes: 15 additions & 2 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -2392,18 +2392,31 @@ Document.prototype.$__validate = function(pathsToValidate, options, callback) {

function _handlePathsToValidate(paths, pathsToValidate) {
const _pathsToValidate = new Set(pathsToValidate);
const parentPaths = new Map([]);
for (const path of pathsToValidate) {
if (path.indexOf('.') === -1) {
continue;
}
const pieces = path.split('.');
let cur = pieces[0];
for (let i = 1; i < pieces.length; ++i) {
_pathsToValidate.add(cur);
// Since we skip subpaths under single nested subdocs to
// avoid double validation, we need to add back the
// single nested subpath if the user asked for it (gh-8626)
parentPaths.set(cur, path);
cur = cur + '.' + pieces[i];
}
}
return paths.filter(p => _pathsToValidate.has(p));

const ret = [];
for (const path of paths) {
if (_pathsToValidate.has(path)) {
ret.push(path);
} else if (parentPaths.has(path)) {
ret.push(parentPaths.get(path));
}
}
return ret;
}

/**
Expand Down
6 changes: 4 additions & 2 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8827,14 +8827,16 @@ describe('document', function() {

it('handles validating single nested paths when specified in `pathsToValidate` (gh-8626)', function() {
const nestedSchema = Schema({
name: { type: String, validate: v => v.length > 2 }
name: { type: String, validate: v => v.length > 2 },
age: { type: Number, validate: v => v < 200 }
});
const schema = Schema({ nested: nestedSchema });
const Model = mongoose.model('Test', schema);

const doc = new Model({ nested: { name: 'a' } });
const doc = new Model({ nested: { name: 'a', age: 9001 } });
return doc.validate(['nested.name']).then(() => assert.ok(false), err => {
assert.ok(err.errors['nested.name']);
assert.ok(!err.errors['nested.age']);
});
});
});

0 comments on commit 3eee840

Please sign in to comment.