mongodb - 在 API 请求 Mongodb 中减去文档中的值
问题描述
帮助我卡住的人。首先我是一个初学者。这是我的第一个反应项目
我有一个带有 f_name、l_name 的表单,订单订单是一个订单数组,我试图遍历它并找到相应的产品,然后减去可用库存中该订单的数量。
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 / of
或者Array.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);
这将并行运行每个语句,这可能会导致数据库负载增加,但速度会更快。权衡取决于将发送多少更新、数据库速度和其他一些因素。
推荐阅读
- java - Java SSL 握手失败
- javascript - 全局属性“未定义”的阴影
- objective-c - 在 Objective-C 中以编程方式创建 Mojave Cocoa 窗口
- r - 带有 Shiny 模块的 updateTabsetPanel
- python - 如何在 python 中使用不同的 SQL 字符串行而不在我的代码中出现错误?
- html - 当视图差异太大时,是否可以将 display:none 用于响应式网站?
- html - 如何使用量角器 - Angular 在第三方包中对数据进行 E2E 测试
- rxjs - 完成之前的可观察对象后,如何强制 RxJs 处理我的可观察对象?
- c# - 如何更改asp.net核心视图
- c# - 尝试使用 Select with MailboxSettings.Read 获取我的 MailboxSettings 时访问被拒绝