Encountering a bad request error while attempting to update a numeric value in MongoDB

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

Answer №1

Here is a solution that should meet your needs:

When forming your request body, ensure it looks like this:

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

Instead of sending an object as a string, use the following format:

res.send(result);

For sending data as JSON, follow this structure:

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

To improve error handling on the client side when your service encounters an issue, make sure to include the catch closure in the fetch function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Is there a way to display a JS alert just one time?

How can I display a message to users on LT IE8 encouraging them to upgrade their browser for a better web experience? I only want the message to appear on their first visit, not every time they refresh the page. Is there a solution for this issue? Thank ...

I am looking to show images based on the number chosen from the dropdown menu in CodeIgniter

When a number is selected from the dropdown menu, I want to display images accordingly. The options in the dropdown are 9, 12, and 18. Here is the code snippet for my view page: <form action="<?php echo base_url();?>roxcontrol/numberdisplay" id=" ...

Retrieve data from an external website containing an HTML table without a table ID using Java Script and transform it into JSON

I have developed a script that can convert HTML table data into a JSON Object. To accomplish this task, I utilized the jquery plugin created by lightswitch05. With this code, I am able to extract data from an HTML table on the same web page using: var t ...

Is there a way to transform these into five columns within a single row using the Material-UI Grid system?

I'm trying to align 5 columns in one row, but I'm struggling to achieve the desired layout. Here is what I currently have: https://i.stack.imgur.com/d3z3n.png Any tips on how to make all columns appear in a single row? You can also view my att ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

What is the best way to organize a data tree in JavaScript for easy parsing on the frontend?

I'm struggling with a unique tree data structure in my code. Each node is represented by an object, and I need to transfer the entire tree to the front-end. Unfortunately, JavaScript's limitation on using objects as keys prevents me from implemen ...

Fetching server-side JavaScript source from a relative path within an ASP file

My setup involves a local IIS server pointing to a virtual workspace at c:\projects Within my c:\projects directory, I have the following folder structure: Game src asp test.asp jquery jquery.min.js The test ...

Convert grouped data in Javascript into a JSON array

After implementing the code snippet provided below, I successfully managed to group objects from my existing dataset using Underscore JS. The grouped data is displayed in distinct groups as depicted by the output: {Group1: Array[10], Group2: Array[13], G ...

Struggling with integrating Skybox in THREE.js

My console is not showing any errors. I am utilizing the live server VS code extension to execute the JS code. Can someone please assist me?" HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

pressure exerted on the body

Recently, I've been working on a project for the website . One of the main issues I've encountered is that the <body> element is consistently 20px lower than it should be at the top. This has led to visible problems with the background grad ...

Tips for incorporating environment variables within a node configuration file

Assuming I have an environment variable $KEY Currently, I am executing KEY=$KEY babel-node build.js //using webpack to create a bundle of my code An issue arises in the JavaScript files bundled by webpack due to an import statement pointing to config.j ...

Creating reactive data in a Vue.js 2 component

I'm currently learning Vue.js 2. I encountered an issue with my code while receiving dynamic data from a server (using Laravel 5.3). The problem arises when I attempt to declare the users array within the component instead of declaring it in the Vue() ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

What is the best way to identify when a cell has been modified in ng-grid aside from just relying on the ng-grid event

My web application features an editable ng-grid that has greatly simplified my work, but I have encountered a minor issue. I need a way to detect when a user makes changes to the grid without having to compare each field before and after. Currently, I am ...

Deleting a li element within an AJAX response function can be accomplished by targeting the specific

I am attempting to remove the li element that is the parent of the clicked a element. Here is the code I am using: function vanish(id_arg){ $.ajax({ url: "/vanish/", type: "POST", data: {id_to_delete: id_arg}, ...

Retrieve the Vue.js JavaScript file from the designated static directory

This is my inaugural attempt at creating a web application, so I am venturing into Vue.js Javascript programming as a newcomer. I have chosen to work with the Beagle Bootstrap template. Within my Static folder, I have a file named app-charts-morris.js whi ...

I can't figure out why my unslider isn't adapting to the screen size. Check out the fiddle for more details

I recently implemented unslider to create a slideshow that spans 100% of the width on my website. Everything seemed to be working fine until I tried resizing the screen, and the slides remained the same size as they were initially loaded. Here is the code ...

Unable to locate node module when using Npm.require

I've been attempting to utilize the Npm.require method in order to access the ldapjs module for client authentication. Unfortunately, I'm encountering the following error message: var ldap = Npm.require('ldapjs'); Error: Cannot find ...

Display checkboxes on all TableRow elements as soon as one of them is checked

I've incorporated a material-ui Table into my project and have successfully implemented multi-select functionality. Here are the requirements I've fulfilled so far: Checkboxes are initially hidden - COMPLETED Hovering over a row reveals its che ...