【问题标题】:Joi Array validation unable to cast to arrayJoi 数组验证无法转换为数组
【发布时间】:2019-12-23 17:23:14
【问题描述】:

我正在使用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;
}

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

{
  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"

我不知道这里发生了什么。你能提出一个解决方案吗?

【问题讨论】:

  • 打印出你的user对象。
  • @hoangdv 用user object 更新了问题

标签: node.js express joi


【解决方案1】:

Joi 架构根据官方文档是正确的。问题出在我的 Mongoose Schema 上。以前是:

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

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 2017-07-28
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多