![](/img/trans.png)
[英]How to update multiple objects in array in a single mongodb document using mongoose
[英]How to update an array in MongoDB using mongoose?
我有兩個模式,用戶和產品。 用戶架構是我存儲所有產品 ID 和用戶添加到購物車的商品數量的地方。
當用戶向“/checkout”發出請求時,它應該更新數量,然后將其從購物車中刪除。 當我結帳數量未更新數量時遇到問題。
router.post('/checkout', auth, catchAsync(async (req, res) => {
const user = await User.findById(req.session.userId);
const err = [];
if (user && user.products.length > 0) {
user.products.map(async (product) => {
let total = 0;
const p = await Product.findById(product.productID);
if (p.quantity > 0 && p.quantity > product.quantity) {
console.log('IN');
total = p.quantity - product.quantity;
console.log(total);
await Product.findOneAndUpdate({ _id: product.productID }, { $set: { quantity: total } });
} else {
err.push(`Item, ${p.name} is sold out`);
}
});
await User.findOneAndUpdate({ _id: req.session.userId }, { $set: { products: [] } });
if (err.length) {
return res.status(500).json({ message: err });
}
return res.status(200).json({ message: 'OK' });
}
return res.status(200).json({ message: 'Empty cart' });
}));
用戶架構:
產品架構:
我相信您的代碼中的問題出在user.products.map(...)
函數上,因為您永遠不會等待您在地圖中創建的所有承諾都得到解決。
換句話說, map
函數返回一個待處理的 promise 數組,但它不會等待它們完成,因此執行會繼續執行到res.status(...)
map
代碼已被執行。
您有不同的選擇來解決它,但主要是您需要處理map
函數返回的承諾數組,並在結束代碼之前等待它們完成。 在Google Developers Web 基礎指南 中對如何使用async/await
處理這種情況有一個很好的解釋。
我通常利用Promise.all()
函數,它從承諾數組中返回一個承諾,因此您可以等到map
的代碼對數組中的每個項目(即您的情況下的product
)並行執行。 您可以在MDN 文檔 中閱讀有關它的更多信息。
// ...
let promisesArray = user.products.map(async product => {...});
// promisesArray should look like: [Promise { <pending> }, Promise { <pending> }, … ]
// Using Promise.all we wait for each of them to be done in parallel
await Promise.all(promisesArray);
// Now you are certain the code in the map has been executed for each product
// ...
一個好的做法是在Promise.all()
周圍使用try {} catch(err) {}
塊來處理某些 promise 被拒絕的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.