Mongoose: Required array field throws error when set as empty array

Created on 10 Feb 2015  ·  3Comments  ·  Source: Automattic/mongoose

I have an array field with the following schema on that field:

parents:
    type: 'Array'
    required: true

When I try to create a document with the following data:

data =
    parents: []

Translation.create data, (err, translations) ->
    console.log err, translations

I get the following error:

ValidationError: Path `parents` is required.

If I put a value inside the array it works, like so:

data =
    parents: ['blah']

Similarly, if I remove the required: true from the schema, it also starts working.

Is an empty array not considered satisfactory for "required" validation? I understand it's false in javascript, but there are plenty of cases where empty arrays and objects are intended in Mongo documents.

backwards-breaking

Most helpful comment

Agree that required array fields should accept empty arrays. I've always thought of it this way, till I had an issue with Mongoose yesterday.

All 3 comments

Agreed, we got tripped up on this too.

Assumed behavior of required: true for us was the presence of an array, rather than an array that requires at least one element.

Agree that required array fields should accept empty arrays. I've always thought of it this way, till I had an issue with Mongoose yesterday.

Gonna close this in favor of #5139. Will change this behavior in 5.0.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

skotchio picture skotchio  ·  102Comments

mocheng picture mocheng  ·  82Comments

saudelog picture saudelog  ·  79Comments

ChrisZieba picture ChrisZieba  ·  76Comments

fundon picture fundon  ·  42Comments