¿Cómo puedo reducir la cantidad de artículos de un objeto en mongoDb y actualizar en el sitio del servidor al lado del cliente?
Aquí hay un sitio de inventario donde almaceno la cantidad de artículos. Al hacer clic en el botón Actualizar, la cantidad debería reducirse uno por uno. código del sitio del cliente:
const handleQuantity = (itemQuantity) => { console.log(itemQuantity); const count = (itemQuantity - 1); const update = { count }; const url = `http://localhost:5000/item/${itemId}` console.log(url); fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(update) }) .then(res => res.json()) .then(data => setItemQuantity(parseInt(data.count))) } return ( <div className='item mt-5 mx-auto pt-2 w-50'> <div><img width='200px' src={item.img} alt="" /></div> <div className='item-description'> <h3>{item.name}</h3> <p className='m-0'>ID: {item._id}</p> <p>{item.description}</p> <h5>Quantity: {item.quantity}</h5> <h3>Price: ${item.price}</h3> <h5>Supplier Name: {item.supplierName}</h5> <button onClick={() => handleQuantity(item.quantity)}>Delivered</button> </div> </div> );código del sitio del servidor:
app.put('item/:id', async (req, res) => { const id = req.params.id; const quantity = req.body; console.log(quantity); const query = { _id: ObjectId(id) }; const options = { upsert: true }; const updateDoc = { $set: { _id: id, name: item.name, price: item.price, description: item.description, quantity: quantity.quantity, suppierName: item.suppierName, img: item.img } } const result = await itemCollection.updateOne(query, updateDoc, options); res.send(result)