Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda