How can I reduce quantity from an object with JS from mongoDb?

148 Views Asked by At

How can I reduce item quantity from an object in mongoDb and update in server site to client side?

Here is an inventory site where I stock the quantity of the items. clicking on the update button the quantity should reduce one by one. client site code:

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

server site code:

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)
0

There are 0 best solutions below