Skip to content

Commit a9740f8

Browse files
committed
Merge pull request #2492 from LearnBoost/gh-661
When an array is marked as modified, run validators on all children #661
2 parents f78e064 + 9e240b8 commit a9740f8

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/document.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -975,6 +975,18 @@ Document.prototype.validate = function (cb) {
975975
var validating = {}
976976
, total = 0;
977977

978+
// gh-661: if a whole array is modified, make sure to run validation on all
979+
// the children as well
980+
for (var i = 0; i < paths.length; ++i) {
981+
var path = paths[i];
982+
var val = self.getValue(path);
983+
if (val instanceof Array && !Buffer.isBuffer(val)) {
984+
var numElements = val.length;
985+
for (var j = 0; j < numElements; ++j) {
986+
paths.push(path + '.' + j);
987+
}
988+
}
989+
}
978990
paths.forEach(validatePath);
979991
return promise;
980992

test/schema.validation.test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,5 +694,32 @@ describe('schema', function(){
694694
});
695695
});
696696
});
697+
698+
it('should allow an array of enums (gh-661)', function(done) {
699+
var validBreakfastFoods = ['bacon', 'eggs', 'steak', 'coffee', 'butter'];
700+
var breakfastSchema = new Schema({
701+
foods: [{ type: String, enum: validBreakfastFoods }]
702+
});
703+
var Breakfast = mongoose.model('gh-661', breakfastSchema, 'gh-661');
704+
705+
var goodBreakfast = new Breakfast({ foods: ['eggs', 'bacon'] });
706+
goodBreakfast.validate(function(error) {
707+
assert.ifError(error);
708+
709+
var badBreakfast = new Breakfast({ foods: ['tofu', 'waffles', 'coffee'] });
710+
badBreakfast.validate(function(error) {
711+
assert.ok(error);
712+
assert.ok(error.errors['foods.0']);
713+
assert.equal(error.errors['foods.0'].message,
714+
'`tofu` is not a valid enum value for path `foods`.');
715+
assert.ok(error.errors['foods.1']);
716+
assert.equal(error.errors['foods.1'].message,
717+
'`waffles` is not a valid enum value for path `foods`.');
718+
assert.ok(!error.errors['foods.2']);
719+
720+
done();
721+
});
722+
});
723+
});
697724
});
698725
});

0 commit comments

Comments
 (0)