diff --git a/lib/schema/documentarray.js b/lib/schema/documentarray.js index 7ed917cafbf..0e29ac32f8b 100644 --- a/lib/schema/documentarray.js +++ b/lib/schema/documentarray.js @@ -79,8 +79,8 @@ DocumentArray.prototype.doValidate = function (array, fn, scope) { SchemaType.prototype.doValidate.call(this, array, function (err) { if (err) return fn(err); - var count = array && array.length - , error; + var count = array && array.length; + var error; if (!count) return fn(); @@ -92,16 +92,16 @@ DocumentArray.prototype.doValidate = function (array, fn, scope) { // sidestep sparse entries var doc = array[i]; if (!doc) { - --count || fn(); + --count || fn(errors); continue; } ;(function (i) { doc.validate(function (err) { - if (err && !error) { - return fn(error = err); + if (err) { + error = err; } - --count || fn(); + --count || fn(error); }); })(i); } diff --git a/test/schema.validation.test.js b/test/schema.validation.test.js index 1a3dec261d4..a601a90d158 100644 --- a/test/schema.validation.test.js +++ b/test/schema.validation.test.js @@ -754,5 +754,19 @@ describe('schema', function(){ done(); }); }); + + it('handles multiple subdocument errors', function(done) { + var foodSchema = new Schema({ name: { type: String, required: true, enum: ['bacon', 'eggs'] } }); + var breakfast = new Schema({ foods: [foodSchema] }); + + var Breakfast = mongoose.model('gh-2589', breakfast, 'gh-2589'); + var bad = new Breakfast({ foods: [{ name: 'tofu' }, { name: 'waffles' }] }); + bad.validate(function(error) { + assert.ok(error); + assert.ok(error.errors['foods.0.name']); + assert.ok(error.errors['foods.1.name']); + done(); + }); + }); }); });