This code block:
await order.forEach((order) => {
let newProduct = Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
newProduct.save();
});
Is probably not working as you would expect it. While it is valid code, it will not wait for each update to execute.
There are a few options - for / of
or Array.map()
that will work closer to how you would expect. See: Using async/await with a forEach loop for more details.
for (order of orders) {
await Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
}
Note this will run serially, updating one product at a time. This will be slower than .map
which will run in parallel and would look like this.
const productUpdates = orders.map(order =>
Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
)
await Promise.all(productUpdates);
This will run each statement in parallel, which can cause more load on your database but will be faster. The tradeoffs depend on how many updates will be sent, database speed, and some other factors.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…