如何将来自邮递员的对象作为数字推送(validationError)?
How to push an object coming from postman as a number(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';
}
})
});
由于错误是需要数量 属性 的验证错误,当您将这两个属性作为单独的对象推送时,它可能无法通过验证,因为您将在 userOrders
数组每个仅包含 productId 或数量
我的主要问题是我无法将数量推送到其各自的对象。我在邮递员中以 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';
}
})
});
由于错误是需要数量 属性 的验证错误,当您将这两个属性作为单独的对象推送时,它可能无法通过验证,因为您将在 userOrders
数组每个仅包含 productId 或数量