我正在使用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"
我不知道这里发生了什么。您能为此提出解决方案吗?
答案 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 }
)
);