Home > Back-end >  How to update data in mongodb database and show in ui
How to update data in mongodb database and show in ui

Time:05-09

Client-side code...!!!
I want to update the quantity by clicking the Delivered button...

In this section have quantity that i'm show bring database.

const [reload, setReload] = useState(true);
const [stock, setStock] = useState({});
const { _id, quantity } = stock;

useEffect(() => {
    const url = `http://localhost:5000/stock/${inventoryId}`;
    fetch(url)
      .then((res) => res.json())
      .then((data) => setStock(data));
  }, [reload]);

In this function I want to update quantity that i'm decrising by clicking button

  const handleDelivered = () => {
    const updateQuantity = parseInt(quantity) - 1; // *actually I want to decrise quantity by clicking Delivered button*

    const url = `http://localhost:5000/stock/${inventoryId}`;
    fetch(url, {
      method: 'PUT',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify(updateQuantity), // *I don't know it's right or wrong and it's so important*
    })
      .then((res) => res.json())
      .then((data) => {
        setReload(!reload);
        setStock(data);
        console.log(data);
      });
  };

return <button onClick={handleDelivered}>Delivered</button>

Server-side code...!!!
On server-side I want to update just the quantity value...

app.put('/stock/:id', async (req, res) => {
      const id = req.params.id;
      const updateQuantity = req.body;
      const filter = { _id: ObjectId(id) };
      const options = { upsert: true };
      const updateDoc = {
        $set: {
          updateQuantity, // *I'm not sure how to set it database. But I want to update quantity value*
        },
      };
      const result = await stockCollection.updateOne(filter, updateDoc, options);
      res.send(result);
    });

CodePudding user response:

You need to set the updatedQuantity on the "quantity" field of the database. You need to change the "updateDoc" object like this in your server-side code:

const updateDoc = {
        $set: {
          quantity: updateQuantity,
        },
      };

Hope this should work.

CodePudding user response:

Client-side code

const handelUpload = (e) => {
e.preventDefault();
const storeQuantity = parseInt(product?.quantity);
const newQuantity = parseInt(e.target.quantity.value);
const quantity = storeQuantity   newQuantity;
if (quantity > 0) {
  fetch(`http://localhost:5000/stock/${inventoryId}`, {
    method: "PUT",
    headers: {
      "Content-type": "application/json; charset=UTF-8",
    },
    body: JSON.stringify({ quantity }),
  })
    .then((response) => response.json())
    .then((data) => {
      console.log("success", data);
      alert("users added successfully!!!");
      e.target.reset();
      setIsreload(!isReload);
    });
} else {
  console.log("input number");
}

};

Server side code api

    app.put("/stock/:id", async (req, res) => {
  const id = req.params.id;
  const updatedProduct = req.body;
  console.log(updatedProduct.quantity);
  console.log(typeof updatedProduct.quantity);
  const filter = { _id: ObjectId(id) };
  const options = { upsert: true };
  const updatedDoc = {
    $set: {
      // name: updatedProduct.name,
      // email: updatedProduct.email,
      quantity: updatedProduct.quantity,
      // price: updatedProduct.price,
    },
  };
  const result = await stockCollection.updateOne(filter,updatedDoc,options
  );
  res.send(result);
});
  • Related