如何将来自邮递员的对象作为数字推送(ValidationError)?
我的主要问题是无法将数量推送到其各自的对象。我以JSON格式在邮递员中发布数据,如下所示:
"productId":"621256596fc0c0ef66bc99ca",
"quantity":10
我的架构是:
userOrders:[
{
productId:{
type: String,
required: [true, "ProductId is required"]
},
quantity:{
type: Number,
required: [true, "Quantity is required"]
}
}
]
我的控制器是:
module.exports.createOrder = async (data) => {
let id = data.userId;
let product = data.productId;
let oQuantity = data.quantity;
return User.findById(id).then(user =>{
user.userOrders.push({productId:product})
user.userOrders.push({quantity:oQuantity})
return user.save().then((savedOrder, err) => {
if (savedOrder) {
return savedOrder;
} else {
return 'Failed to create order. Please try again';
}
})
});
我收到如下错误:
this.$__.validationError = new ValidationError(this);
^
ValidationError: User validation failed: userOrders.0.quantity: Quantity is required
我试了那么多东西,但还是解决不了。有什么建议吗?
解决方案
不是将两个单独的对象推入userOrders
数组,而是推入一个同时具有两个属性的对象。
module.exports.createOrder = async (data) => {
let id = data.userId;
let product = data.productId;
let oQuantity = data.quantity;
User.findById(id).then(user =>{
const data = {
productId: product,
quantity: oQuantity
}
user.userOrders.push(data)
user.save().then((savedOrder, err) => {
if (savedOrder) {
return savedOrder;
} else {
return 'Failed to create order. Please try again';
}
})
});
由于该错误是需要Quantity属性的验证错误,因此当您将这两个属性作为单独的对象推送时,它可能无法通过验证,因为您将在userOrders
数组中有两个单独的对象,每个对象仅具有ProductID或Quantity
相关文章