我如何使用 Mongo DB 的数据库使用按钮的 put 方法从项目中减去和添加数量?

How can I use Mongo DB's database to subtract and add a quantity from an item using the put method from a button?

我的代码有什么问题?
我实际上想通过一个按钮减少和增加某些项目的数量,但我不明白代码有什么问题。所以我是来帮忙的。请帮助任何人。谢谢

 **server side**
        
        ** PUT METHODS**
            app.put("/items/:id", async (req, res) => {
              const id = req.params.id;
              const updateItemData = req.body;
              const filter = { _id: ObjectId(id) };
              const option = { upsert: true };
              const updateItemDoc = {
                $set: {
                  quantity: updateItemData.itemQuantity,
                },
              };
              const result = await itemsCollection.updateOne(
                filter,
                option,
                updateItemDoc
              );
        
              res.send(result);
            });
          } finally {
          }
        };
        **client side**`enter code here`
         useEffect(() => {
            fetch(`http://localhost:5000/items/${itemId}`)
              .then((response) => response.json())
              .then((data) => setItem(data));
          }, []);
        
          const handleItemDelivered = (quantity) => {
            const newQuantity = item.quantity - 1;
            console.log(newQuantity);
            const { itemQuantity } = newQuantity;
            console.log(parseInt(newQuantity));
            const url = `http://localhost:5000/items/${itemId}`;
            fetch(url, {
              method: "PUT",
              headers: {
                "content-type": "application/json",
              },
              body: JSON.stringify(itemQuantity),
            })
              .then((response) => response.json())
              .then((datenter code herea) => setItem(data));
            alert("quantity-updated successfully");
          };

由于要增加和减少计数,最佳做法是使用 $inc 而不是 $set。这是一个原子操作,允许您从多个客户端“并行”更新,即它们不会覆盖 each-other:

const updateItemDoc = {
                $inc: {
                  quantity: updateItemData.deltaQuantity,
                },
              };