Home > Net >  Getting bad request error when updating a number in MongoDB
Getting bad request error when updating a number in MongoDB

Time:05-08

I was trying to update a single element(which is a number) that 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 an object of the 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