Joi阵列验证无法转换为阵列

时间:2019-12-23 08:31:56

标签: node.js express joi

我正在使用Joi进行架构验证。我有一个要使用Joi进行验证的对象数组。这是代码:

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

这是我传递给user函数的validateUser对象。

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

但是,它向我显示了以下错误。

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"

我不知道这里发生了什么。您能为此提出解决方案吗?

1 个答案:

答案 0 :(得分:0)

根据官方文档,

Joi模式是正确的。问题出在我的Mongoose模式上。以前是:

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

当我将其更改为:时效果很好

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