Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

Joi Array validation unable to cast to array

I am using Joi for schema validation. I have an array of object's that i want to be validated with Joi. Here is the code:

const joi = require("joi");

function validateUser(user) {
  let phone = joi.object().keys({
    id: joi.string().required(),
    phoneNumber: joi.string().required()
  });

  const schema = {
    firstName: joi.string().required(),
    lastName: joi.string().required(),
    email: joi
      .string()
      .email()
      .required(),
    phoneNumbers: joi.array().items(phone)
  };

  return joi.validate(user, schema).error;
}

This is the user object that i am passing to validateUser function.

{
  firstName: 'User',
  lastName: 'One',
  email: '[email protected]'
  phoneNumbers: [
    {
      id: '03bb22cc-499a-4464-af08-af64d5a52675',
      phoneNumber: '13001234567'
    },
    {
      id: '50e32458-756b-4aaa-b3dc-19a2f696ab6c',
      phoneNumber: '13031234567'
    }
  ]
}

But, it is showing me the following error.

UnhandledPromiseRejectionWarning: ValidationError: user validation failed: phoneNumbers: Cast to Array failed for value "[
  {
    id: '03bb22cc-499a-4464-af08-af64d5a52675',
    phoneNumber: '13001234567'
  },
  {
    id: '50e32458-756b-4aaa-b3dc-19a2f696ab6c',
    phoneNumber: '13031234567'
  }
]" at path "phoneNumbers"

I don't know what is happening here. Could you please propose a solution to this?

Upvotes: 1

Views: 830

Answers (1)

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

Joi schema is correct according to the Official Documentation. The issue was with my Mongoose Schema. Previously it was:

const User = mongoose.model(
  "user",
  new mongoose.Schema(
    {
      firstName: {
        type: String,
        required: true
      },
      lastName: {
        type: String,
        required: true
      },
      email: {
        type: String,
        required: true
      },
      phoneNumbers: {
        type: [String],
        default: []
      }
    },
    { timestamps: true }
  )
);

It worked fine when i changed it to:

const User = mongoose.model(
  "user",
  new mongoose.Schema(
    {
      firstName: {
        type: String,
        required: true
      },
      lastName: {
        type: String,
        required: true
      },
      email: {
        type: String,
        required: true
      },
      phoneNumbers: {
        type: [{ id: String, phoneNumber: String}],
        default: []
      }
    },
    { timestamps: true }
  )
);

Upvotes: 1

Related Questions