[英]Part of the API is not working in NodeJS. How do I fix it?
我正在尝试在 NodeJS 中为在线商店构建 REST API。 我的 POST 请求代码如下所示:
router.post('/', (req, res, next) => {
const order = new Order({
_id: new mongoose.Types.ObjectId(),
customer_name: req.body.order.customer_name,
total_price: req.body.order.total_price,
products: req.body.order.products,
});
order
.save()
.then(result => {
req.body.order.products.forEach(value => {
let availiableQuantity = value.available_quantity - value.ordered_quantity;
Product.findOneAndUpdate({ id: value.id }, { available_quantity: availiableQuantity
})
})
res.status(201).json({
message: "Successfully created product",
createdProduct: {
customer_name: result.customer_name,
products: result.products,
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
我遇到的问题是,当我尝试发送此 POST 请求时, .then块中的代码不起作用,即使我尝试使用 console.log 进行某些操作,它也不会执行任何操作,除了.then块中的代码:
.then(result => {
console.log('test')
req.body.order.products.forEach(value => {
let availiableQuantity = value.available_quantity - value.ordered_quantity;
Product.findOneAndUpdate({ id: value.id }, { available_quantity: availiableQuantity
})
})
我错过了什么吗?
您可以改为使用 async await 而不是使用 then 块处理下一步。
router.post('/',async (req, res) => {
try{
const order = new Order({
_id: new mongoose.Types.ObjectId(),
customer_name: req.body.order.customer_name,
total_price: req.body.order.total_price,
products: req.body.order.products,
});
var result = await order.save();
req.body.order.products.forEach(value => {
let availiableQuantity = value.available_quantity -
value.ordered_quantity;
Product.findOneAndUpdate({ id: value.id }, {
available_quantity: availiableQuantity
})
res.status(201).json({
message: "Successfully created product",
createdProduct: {
customer_name: result.customer_name,
products: result.products,
}
});
} catch(e) {
res.status(500).json({
message: "Bad request",
error: e
});
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.