Update only one field at a time using the REST API

Currently, I am developing an inline grid editor that triggers a call to an express rest api whenever a user updates a single value in the grid. The issue I am facing is that when a field is changed, my PATCH request attempts to update all fields instead of just the one that was modified. This causes any fields with no value to be set as NULL in the database. What I aim to achieve is to only update the specific field that is passed into the API, which could be any field. Below is the method I am using for patching:

// Update record based on TxnID
router.patch('/editablerecords/update', function (req, res) {
    let qb_TxnID = req.body.txnid
    let type = req.body.type;
    let margin = req.body.margin;

    if (!qb_TxnID) {
        return res.status(400).send({ error:true, message: 'Please provide TxnID' });
    }

    connection.query("UPDATE pxeQuoteToClose SET ? WHERE qb_TxnID = '" + qb_TxnID + "'", { type, margin  }, function (error, results, fields) {
        if(error){
            res.send(JSON.stringify({"status": 500, "error": error, "response": null })); 
        } else {
            res.send(JSON.stringify({ error: false, data: results, message: 'Record updated.' }));
        }
    });
});

I intend to update only one field at a time, either type or margin, without affecting the other (if not specified). If only one field is sent, the unmentioned field will default to null. I have researched the connection.query() method, but details about how it constructs the query are unclear. It seems every req.body.value influences the query.

This is my first attempt at building a REST API and I suspect there might be a simple solution eluding me.

EDIT: It's worth mentioning that while I may eventually need to update both fields, currently I prefer updating them individually. Thank you.

Answer №1

According to the guidelines outlined in RFC specifications, when making a PATCH call, the body should not contain the updated representation of the resource but rather a set of instructions on how to modify the resource.

The PATCH method involves applying a series of changes specified in the request entity to the resource identified by the Request-URI. These changes are provided in a "patch document" format associated with a specific media type.

A recommended standard for implementing PATCH requests with JSON can be explored at this link. An example patch document following this standard may include:

   [
     { "op": "test", "path": "/a/b/c", "value": "foo" },
     { "op": "remove", "path": "/a/b/c" },
     { "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
     { "op": "replace", "path": "/a/b/c", "value": 42 },
     { "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
     { "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
   ]

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

Ways to switch up the titles on UploadThing

Recently, I started working with the UploadThing library and encountered a situation where I needed to personalize some names within the code. Here is what I have so far: Below is the snippet of code that I am currently using: "use client"; imp ...

Error in JSON due to the presence of an unexpected token within the

I am facing a challenge with my PHP code, where I take a list of filenames or empty strings and store them in an array. This array is then converted to JSON and saved in a database successfully. However, the problem arises when this array is also stored wi ...

Create a JSON file on the fly

I am in need of performing a post request using a JSON file. The current structure of the JSON is as follows: { "compositeRequest" : [{ // Account "method" : "POST", "url" : &quo ...

How to make a form in PHP that can be saved?

I have put together a straightforward, yet lengthy HTML form and I am in need of a way for users to save their progress on the form and return to it at a later time (security is not a major concern). However, I am struggling with how to save the form' ...

Sending an error from one asynchronous function to another

I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function. Unfortunately, I've been unable to successfu ...

Use Mongoose to check for a document, apply filters, and update if found. If not found,

My current approach involves searching for a document using a provided email address in the following method. If the document is found, I aim to update the _id field. Otherwise, I create a completely new document. function (accessToken, refreshToken, prof ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Place the bottom element of the top parent element in position

Creating a simple tooltip with bottom positioning at the top of the parent element involves setting a negative height for the tooltip element. However, when checking the height of the tooltip element upon hovering, it returns 0 according to console.log(). ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Accessing the current frame of a video in JavaScript or jQuery

Currently, I am experimenting with the HTML video tag to play a video. Instead of retrieving the "currentTime" of the video, I am interested in obtaining the current frame using either jQuery or JavaScript. Despite my efforts in calculating the frame rate ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

What is the best way to create a sharp light effect on a sphere in three.js?

My three.js scene features a sphere and directional light. The sphere appears to gradually darken as you look at it. How can I speed up the transition from light to dark? Is there a way to make the light appear "sharper"? var scene, camera, renderer, co ...

There appears to be an issue with reading the property 'toLowerCase' of an undefined element, and I'm having trouble identifying the error

The variables I have initialized (globally): var audio; var LANGUAGE; var audioArray; var MEDIAARRAY; var WORDS; var SOUNDARRAY; This specific line is causing the error: var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInpu ...

Organizing items within a group

As I embarked on my journey of creating my first Meteor app, I encountered a challenge that left me feeling a bit lost. I have a collection of Entries and I want to categorize them by date, not simply sort them. Each entry comes with a date and I envision ...

Return to the main page by clicking on the link #id

I am in the process of creating a personalized Wordpress theme that consists of one main page with 8 additional sub-pages. I am wondering how I can navigate to a specific section using an ID (for example, <a href="#how">how</a>) from the sub-pa ...

Exploring the contrast between Vuex store WATCH and SUBSCRIBE

Can you explain the main distinction between watch and subscribe, and when it is most appropriate to use one over the other? According to information on the Vuex official documentation, both methods appear to be essentially identical in functionality and p ...

Seeking assistance with jQuery/AJAX syntax, any pointers

In my project, I have created two forms, one called 'table' and the other called 'fields'. The 'fields' form is designed to display options based on the selection made in the 'table' form, using an Ajax request. I ha ...

Polymer Integrated Binding for Advanced Search Options

Here is my code snippet to bind a tree in the Office->Team->"user" hierarchy. The main requirement is to enable user search functionality. To bind the tree, I have processed the users array to fit the required hierarchy. For searching, I filter out ...

Installing NPM packages by hand

I recently used the node windows installer v0.8.3 to set up nodejs on my system. However, when attempting to install express by running the command: npm install express I encountered issues. I suspect the problem lies with my company's proxy setting ...