5

In my schema I need to have a propery that is an array that must be always not null and not undefined.

So I defined it required, but the validation is not working as I expected, because if I omit the property no error is throw.

In case of simple property (not an array) this work as I expected

const nodeSchema = new Schema({
    address: { type: String, required: true },
    outputs: { type: [String], required: true }
})
Marco24690
  • 305
  • 1
  • 4
  • 23

4 Answers4

7

I think you can fix it adding a custom validator like this:

const nodeSchema = new Schema({
    address: { type: String, required: true },
    outputs: {
      type: [String],
      required: true,
      validate: [(value) => value.length > 0, 'No outputs'],
    }
})

I hope it helps you.

ILoveYouDrZaius
  • 239
  • 3
  • 8
1

Just add the "default" as undefined and it will validate the array properly:

const nodeSchema = new Schema({
  address: { type: String, required: true },
  outputs: { type: [String], required: true, default: undefined },
})
Rafael Grilli
  • 1,959
  • 13
  • 25
0

Arrays implicitly have a default value of [] (empty array).

This was the problem

Marco24690
  • 305
  • 1
  • 4
  • 23
0

Array implicitly have a default value of [] (empty array). if you add default: undefined it will fix the issue.