Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Cómo actualizar datos en la base de datos mongodb y mostrar en ui

Código del lado del cliente...!!!
Quiero actualizar la cantidad haciendo clic en el botón Entregado...

En esta sección, tengo la cantidad que muestro para traer la base de datos.

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

En esta función, quiero actualizar la cantidad que estoy declarando haciendo clic en el botón

 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>

Código del lado del servidor...!!!
En el lado del servidor, quiero actualizar solo el valor de la cantidad...

 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); });
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Debe establecer la cantidad actualizada en el campo "cantidad" de la base de datos. Debe cambiar el objeto "updateDoc" de esta manera en su código del lado del servidor:

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

Espero que esto funcione.

over 4 years ago · Santiago Trujillo Report

0

Código del lado del cliente

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

API de código del lado del servidor

 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); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!