首页 > 解决方案 > 在 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);
  }
});

标签: mongodbmongoose

解决方案


此代码块:

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);

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


推荐阅读