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

Trouble with retrieving JSON data?

Struggling to access the JSON object issue: Received JSON Object: {"71":"Heart XXX","76":"No Heart YYYY"} I attempted to retrieve values for 71 and 72 individually but encountered compile time problems as: Syntax error on token ".71", delete this token ...

Javascript menu toggle malfunctioning with sub-menus

I am in the process of creating a responsive menu for a complex website. The horizontal menu transitions into a vertical layout on smaller screens, with javascript used to toggle the sub-menu items open and closed when clicked. One issue I am facing is wit ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

Troubleshooting "Not Found" Error on Heroku/Express Sub-Route When Refreshing the Page

I currently have a React Web App deployed on Heroku, which is being served by an Express/Node.js server. When a user attempts to access any route on my server, the index.js file executes the following code: const path = require('path') app.get(& ...

Refreshing Angular Page

I'm looking for a way to reset my Angular page back to its original state with just one button click. I attempted to use the angular.copy method, but encountered an error. I have various scope and controller variables that I don't want to reset i ...

Shifting Icon to the Right within the Drawer Navigator Toolbar

While modifying the example code for Material UI's drawer navigator, I decided to enhance it by adding a notification icon and a checkout icon with the Admin Panel typography in the toolbar. However, I encountered an issue where the checkout icon app ...

Steps for toggling between enabling and disabling the 2 instances of bvalidator

Running on my form are two instances of bvalidator found at . The first instance validates the entire form, while the second instance only partially validates the same form. In total, the form contains 2 buttons: The first button saves form data upon va ...

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

NextJS will redirect the user back to the previous router they came from following authentication

Hello! I am currently facing a challenge in redirecting a user back to the initial page they clicked on after being authenticated. The issue lies in server-side rendering (SSR) and the lack of access to the window.history object in getServerSideProps. The ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions? <Table responsive> <thead> <tr> ...

Error TS2346: The parameters provided do not match the signature for the d3Service/d3-ng2-service TypeScript function

I am working with an SVG file that includes both rectangular elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x ...

Transferring extra data from jQuery autocomplete to a PHP script

Hey there! I'm wondering if it's possible to pass extra parameters from jQuery autocomplete to a PHP page, which would then use them to query a database and return the results. While I know how to send the typed term from the input box, I'd ...

Executing JavaScript following an Ajax request

I am faced with a situation where my HTML file utilizes a function for loading another PHP file using Ajax: function LoadContent(n,func) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xm ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...