【发布时间】:2021-09-11 01:39:30
【问题描述】:
我是 nodeJs 的新手,但我已经进行了研究以解决我的问题,但似乎我缺乏异步功能。 我找到了这个解决方案,但它不起作用,我将在下面发布: enter link description here
这是我的代码
router.put("/placeOrder", [auth, isVerified, isExists], async (req, res) => {
try {
const productList = req.body; // body
await Promise.all(
productList.map(async (element) => {
// compare between the inserted element and the store one here
let getItemPrice = await Order.findOne({
_id: element._id,
buyerId: req.user._id,
orderStatus: "PENDING",
});
if (!getItemPrice) {
return res.status(400).json({
status: "failed",
message: "order not exists",
});
}
getItemPrice.items.map(async (item) => {
await Order.findOneAndUpdate(
{
"items.productId": item.productId,
},
{
$set: {
orderStatus: "ACTIVE",
"items.$.itemStatus": "ACTIVE",
paymentMethod: element.paymentMethod,
},
}
);
});
})
);
res.status(200).json({
message: "Order has placed",
});
} catch (error) {
return res.status(400).json({
status: "failed",
message: error.message,
});
}
// update documents
});
我正在尝试检查 Id 是否不存在于我的数组中,如果不存在只是通过 Id 不存在的错误,它工作正常,但它会在日志中保留打印错误: TypeError: Cannot create property 'Symbol(level)' on string 'Cannot set headers after they are sent to the client' 感谢您的时间和整理
【问题讨论】:
-
它为不存在的每个项调用
res.status(400).json(。 -
您可能调用 res.json 两次。只需在每个 res.json 之前添加一个 console.log('send') ,如果您看到两次日志,则需要确保只调用一次。
-
我是否应该在那里进行回调并只打印一次。这会让它工作吗
标签: javascript node.js arrays mongodb mongoose