Skip to content

When an array is marked as modified, run validators on all children #661 #2492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 26, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -975,6 +975,18 @@ Document.prototype.validate = function (cb) {
var validating = {}
, total = 0;

// gh-661: if a whole array is modified, make sure to run validation on all
// the children as well
for (var i = 0; i < paths.length; ++i) {
var path = paths[i];
var val = self.getValue(path);
if (val instanceof Array && !Buffer.isBuffer(val)) {
var numElements = val.length;
for (var j = 0; j < numElements; ++j) {
paths.push(path + '.' + j);
}
}
}
paths.forEach(validatePath);
return promise;

Expand Down
27 changes: 27 additions & 0 deletions test/schema.validation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -694,5 +694,32 @@ describe('schema', function(){
});
});
});

it('should allow an array of enums (gh-661)', function(done) {
var validBreakfastFoods = ['bacon', 'eggs', 'steak', 'coffee', 'butter'];
var breakfastSchema = new Schema({
foods: [{ type: String, enum: validBreakfastFoods }]
});
var Breakfast = mongoose.model('gh-661', breakfastSchema, 'gh-661');

var goodBreakfast = new Breakfast({ foods: ['eggs', 'bacon'] });
goodBreakfast.validate(function(error) {
assert.ifError(error);

var badBreakfast = new Breakfast({ foods: ['tofu', 'waffles', 'coffee'] });
badBreakfast.validate(function(error) {
assert.ok(error);
assert.ok(error.errors['foods.0']);
assert.equal(error.errors['foods.0'].message,
'`tofu` is not a valid enum value for path `foods`.');
assert.ok(error.errors['foods.1']);
assert.equal(error.errors['foods.1'].message,
'`waffles` is not a valid enum value for path `foods`.');
assert.ok(!error.errors['foods.2']);

done();
});
});
});
});
});