Home > Software design >  mongodb returns matchCount 1 but modifiedCount 0
mongodb returns matchCount 1 but modifiedCount 0

Time:05-08

I was making a web app where a card is showing the quantity of a product. There is a button also named Delivered. After clicking the button, I want to decrease the quantity 1. Suppose, a product's quantity is 10. If I click on the Delivered button, the quantity of the product should turn into 9 and also it should update on the mongoDb data base. Fortunetly it worked. But I got a little problem. The problem is, when I click on the button first time mongoDb returns acknowledged: true, modifiedCount: 0, upsertedId: null, upsertedCount: 0, matchedCount: 1 and the data is updating from UI but not updating in the mongoDb server. Then i clicked on the button for second time then mongoDb returns acknowledged: true, modifiedCount: 1, upsertedId: null, upsertedCount: 0, matchedCount: 1. The client site code is given bellow:

const { _id, img, name, seller, price, qnt, description } = product

const [quantity, setQuantity] = useState(qnt);

const handleQnt = () => {
    const numQuantity = Number(quantity);
    setQuantity(numQuantity - 1);

    const url = `http://localhost:5000/update-quantity/${_id}`;

    fetch(url, {
        method: 'PUT',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify({
            qnt: quantity
        })
    })
        .then(res => res.json())
        .then(result => {
            console.log(result);
        });

}
console.log(quantity);

The button code is :

<button onClick={() => handleQnt()} > Delivered </button>

and the server site code is :

 app.put('/update-quantity/:id', async (req, res) => {

        const id = req.params.id;

        const data = req.body;

        const filter = { _id: ObjectId(id) };

        const options = { upsert: true };

        const updatedDoc = {
            $set: {
                qnt: data.qnt
            },

        };

        const result = await camCollection.updateOne(filter, updatedDoc, options);

        res.send(result)
    })

CodePudding user response:

You send quantity from client, but the variable does not reflect changes made by setQuantity(). You should declare let newNumQuantity = numQuantity - 1 and send newNumQuantity to server instead of quantity.

  • Related