Home > Blockchain >  i want to update a number in mongodb but showing bad request
i want to update a number in mongodb but showing bad request

Time:05-08

i was trying to update a single element(which is a number)which is stored in mongodb . here is the request i 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 inside mongodb is object of array. to execute the operation i tried to build an api with express . here is 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);

});

whenever i click on the button to update it shows an error saying PUT(link)400 (bad request) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

CodePudding user response:

This should work for you:

In you request body do this:

body : JSON.stringify({quantity: final})

Instead, send an object as a string whit:

res.send(result);

Send as a JSON like this:

res.status(200).json(result);

And to your client to catch better the error that your service throw add the closure catch to the fetch.

  • Related