Marco24690
Marco24690

Reputation: 355

Mongoose array required in schema validation not working

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 }
})

Upvotes: 5

Views: 2791

Answers (4)

Rafael Grilli
Rafael Grilli

Reputation: 2039

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 },
})

Upvotes: 1

Sakib Rahman
Sakib Rahman

Reputation: 21

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

Upvotes: 1

ILoveYouDrZaius
ILoveYouDrZaius

Reputation: 239

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.

Upvotes: 7

Marco24690
Marco24690

Reputation: 355

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

This was the problem

Upvotes: 0

Related Questions