I attempted to update a single element in mongodb, specifically a number value. Below is the request sent to the DB:
const handleDelivered = (num) =>{
const total = service.quantity;
const final = parseInt(total) + num;
console.log(total,final);
const url = `http://localhost:5000/services/${idOfService}`;
fetch(url,{
method :'PUT',
headers :{
'content-type': 'application/json',
},
body : JSON.stringify(final)
})
.then(res => res.json())
.then(product =>{
console.log(product);
})
}
The data stored in MongoDB is an object within an array. To perform this operation, I tried constructing an API using express. Here's the code for the API:
app.put('/services/:id', async(req,res)=>{
const id = req.params.id;
const filter = {_id : ObjectId(id)};
const options = { upsert: true };
const updatedData = req.body;
const updateDoc = {
$set: {
quantity : updatedData.quantity,
},
};
const result = await serviceCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
However, when attempting to update by clicking on the button, an error message appears:
PUT(link)400 (bad request)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0