我正在制作送货应用程序。 当我尝试在Postman中发布包含所有必需数据的订单请求时,对于每个对象都会收到以下错误:
"message": "order validation failed: recipient.recLocation.recPhone: Path `recipient.recLocation.recPhone` is required., recipient.recLocation.recZipcode: Path `recipient.recLocation.recZipcode` is required., recipient.recLocation.recStreetnumber: Path `recipient.recLocation.recStreetnumber` is required., recipient.recLocation.recStreet: Path `recipient.recLocation.recStreet` is required., recipient.recLocation.recCity: Path `recipient.recLocation.recCity` is required., recipient.recName: Path `recipient.recName` is required.",
所以基本上,我的请求都没有通过。我环顾四周,根据在此之前的答案以及在Google上的发现,我的猫鼬模型和路线文件似乎都很好。 这是该模型中“收件人”的代码段:
recipient: {
//rec in front of field names stands for "recipient" - done so that the data of recipient doesn't get confused for the data of the sender
recName: {
type: String,
required: true
},
recLocation: {
recCity: {
type: String,
required: true,
max: 32
},
recStreet: {
type: String,
required: true,
max: 32
},
recStreetnumber: {
type: String,
required: true,
max: 16
},
recZipcode: {
type: String,
required: true,
max: 16
},
recPhone: {
type: String,
required: true,
max: 32
}
}
}
这是路由文件的摘录:
const orderFields = {};
orderFields.user = req.user.id;
if (req.body.description) orderFields.description = req.body.description;
if (req.body.status) orderFields.status = req.body.status;
//recipient
orderFields.recipient = {};
if (req.body.recName) orderFields.recipient.recName = req.body.recName;
if (req.body.recCity) orderFields.recipient.recCity = req.body.recCity;
if (req.body.recStreet)
orderFields.recipient.recStreet = req.body.recStreet;
if (req.body.recStreetnumber)
orderFields.recipient.recStreetnumber = req.body.recStreetnumber;
if (req.body.recZipcode)
orderFields.recipient.recZipcode = req.body.recZipcode;
if (req.body.recPhone) orderFields.recipient.recPhone = req.body.recPhone;
我猜我设置路径的方式是错误的,但是我是根据谷歌搜索并在这里探索其他问题的发现来做到这一点的。
谢谢!
编辑
This is what I'm trying to pass in Postman
此外,当我将上述代码片段从路由文件更改为:
orderFields.recipient = {};
if (req.body.recName) orderFields.recipient.recName = req.body.recName;
if (req.body.recCity)
orderFields.recipient.recLocation.recCity = req.body.recCity;
if (req.body.recStreet)
orderFields.recipient.recLocation.recStreet = req.body.recStreet;
if (req.body.recStreetnumber)
orderFields.recipient.recLocation.recStreetnumber =
req.body.recStreetnumber;
if (req.body.recZipcode)
orderFields.recipient.recLocation.recZipcode = req.body.recZipcode;
if (req.body.recPhone)
orderFields.recipient.recLocation.recPhone = req.body.recPhone;
我得到了另一个错误: 2nd Postman screenshot
答案 0 :(得分:0)
似乎您应该传递带有分层主体的请求,而不是拼合字段。 recipient
模型描述了一个recLocation
,其中包含5个必填字段,您确实在提供它们-但位置错误。
尝试发布同样描述位置的JSON请求:
recLocation: {
reqCity: "..."
reqStreet: "..."
...
}
答案 1 :(得分:-1)
有详细记录的软件包,Express验证器非常易于实现。您无需在函数内部创建if条件。 请点击this链接。