Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

mongoose - Subtract value in a document in API request Mongodb

Help guys im stuck. First of all im a beginner. This is my first react project

I have a form being sent with f_name, l_name, order order is an array of orders I am trying to loop through it and find the corresponding product then subtract the quantity for that order in the available stocks.


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);
  }
});
question from:https://stackoverflow.com/questions/65907436/subtract-value-in-a-document-in-api-request-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...