diff --git a/lib/schema/string.js b/lib/schema/string.js index bf1b6d85749..cb8b866c115 100644 --- a/lib/schema/string.js +++ b/lib/schema/string.js @@ -242,7 +242,7 @@ SchemaString.prototype.enum = function() { const vals = this.enumValues; this.enumValidator = function(v) { - return undefined === v || ~vals.indexOf(v); + return null == v || ~vals.indexOf(v); }; this.validators.push({ validator: this.enumValidator, diff --git a/test/schema.validation.test.js b/test/schema.validation.test.js index 22fab457bd1..e467f6ea088 100644 --- a/test/schema.validation.test.js +++ b/test/schema.validation.test.js @@ -827,6 +827,19 @@ describe('schema', function() { } }); + it('should allow null values for enum gh-3044', async function() { + const testSchema = new Schema({ + name: { + type: String, + enum: ['test'] + } + }); + const Test = mongoose.model('allow-null' + random(), testSchema); + const a = new Test({ name: null }); + const err = await a.validate().then(() => null, err => err); + assert.equal(err, null); + }); + it('should allow an array of subdocuments with enums (gh-3521)', async function() { const coolSchema = new Schema({ votes: [{