减去API请求Mongodb中文档中的值



帮助那些陷入困境的人。首先,我是个初学者。这是我的第一个反应项目

我收到一张表格,上面有f_name、l_name和订单order是一个订单数组我试图循环浏览它,找到相应的产品,然后减去可用库存中该订单的数量。


let Transaction = require("../models/transactionModel");
let Products = require("../models/userInventoryModel");
router.route("/add").post(async (req, res) => {
const { f_name, l_name, order } = req.body;
try {
const newTransaction = new Transaction({
f_name,
l_name,
order,
});
await order.forEach((order) => {
let newProduct = Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
newProduct.save();
});
await newTransaction.save();
res.status(200).json(newTransaction);
} catch (error) {
res.status(400).json(error.message);
}
});

此代码块:

await order.forEach((order) => {
let newProduct = Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
newProduct.save();
});

可能没有如您所期望的那样工作。虽然它是有效的代码,但它不会等待每次更新执行。

有几个选项-for / ofArray.map()将更接近您的预期。有关更多详细信息,请参阅:将async/await与forEach循环结合使用。

for (order of orders) {
await Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
}

请注意,这将连续运行,一次更新一个产品。这将比并行运行的.map慢,并且看起来像这样。

const productUpdates = orders.map(order =>
Products.findOneAndUpdate(
{ product: order.product },
{ $inc: { stocks: -order.quantity } }
);
)
await Promise.all(productUpdates);

这将并行运行每个语句,这可能会给数据库带来更多负载,但速度会更快。权衡取决于将发送的更新数量、数据库速度和其他一些因素。

相关内容

最新更新