Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
Getting bad request error when updating a number in MongoDB

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
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda