What is the best way to individually update fields using Prisma?

I am facing a challenge with updating fields individually for an object named Post. This object has three fields: title, content, and summary.

Situation

To save a post in the database, I can fill in just the title field initially and leave the other fields empty. The goal is to update these additional fields separately as needed when visiting the post page.

The code snippet on my page is used to update the title only:

    const updateTitleData = async () => {
            try {
                await fetch(`/api/story/${id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(title)
                })
                refreshData()
            } catch (error) {
                toast.error('Document could not be updated')
                console.error(error);
            }
        };

Within the API route, the following code is implemented:

    const storyId = req.query.id
    const {title, content, summary} = req.body
     else if (req.method !== 'PUT') {
            console.log("Note could not be modified")
            res.status(400).json({message: "Note could not be modified"})
        } else {
           await prisma.story.update({
                where: {id: storyId},
                data: {
                    title,
                    content,
                    summary
                }
            })
            res.status(200).json({message: ' updated'})
        }

My current setup seems to be ineffective as no mutation occurs when using this line of code: i.e

const {title, content, summary} = req.body

However, by changing it to individual assignment like this:

const title = req.body
const content = req.body
const summary = req.body

Updating any one field triggers a change, but it updates all fields with the same value. How can I achieve the goal of updating just one field at a time?

Answer №1

Assuming that title is a string. If you pass

body: JSON.stringify(title)

through the API, then req.body will contain a string. Later, if you proceed with

const title = req.body
const content = req.body
const summary = req.body

then all three variables will hold the same string value. Consequently, the post's attributes will be updated uniformly.

Generally, it is advisable to provide something like:

body: {
  title: "new title"
}

when using the API.

In this case, the body becomes an object. Subsequently, if you execute

const {title, content, summary} = req.body

title would be the string new title, while content and summary will be undefined.

You can utilize these values for updating your database accordingly.

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 grant entry to a Vue.js page exclusively to authenticated users or when localStorage is present

My Vue.js application is set up with vue-router as shown below. index.html <p> <router-link to="/" exact> Home </router-link> <router-link to="/about"> About </router-link> <router-link to="/contact"> Contact < ...

Changing the host in every URL within a string using node.js

I am working with a string that contains URLs with IP addresses: { "auth" : { "login" : "http://123.123.11.22:85/auth/signin", "resetpass" : "http://123.123.22.33:85/auth/resetpass", "profile" : "http://123.123.33.44:85/auth/profile" ...

Is it possible to insert an image directly into the <img> tag without having to first send it to the server?

I've created an upload form that allows users to submit images: <form> <input accept="image/jpeg, image/gif, image/png" type="file" name="image" id="image" class="UploadInput" onchange="submitImageUploaderForm()"/> </form> Once t ...

How to extract the value of a key from JSON using JavaScript

Need help with an API call to retrieve a list of subcategories? Here's an example of the JSON format: { "description": "Flower", "name": "Flower", "parent_id": "1" }, { "description": "Moon", "n ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

Component does not display dynamically created DOM elements

I have a function that creates dynamic DOM elements like this: const arrMarkup = []; const getMarkup = () => { if (true) { arrMarkup.push( <Accordion expanded={expanded === cust.name} onChange={handleChange(cust.name)}> ...

Receiving a blank string after calling fs.readFile within the chokidar.watch(path_file).on('change', ...) function

This is my current Node project setup: https://github.com/tlg-265/chokidar-issue https://i.stack.imgur.com/qYKlR.png $ git clone https://github.com/tlg-265/chokidar-issue $ cd chokidar-issue $ npm i $ npm run watch-changes The project monitors changes ...

Safari is causing issues with HTML5 Video playback

I have a client with a media-heavy website containing numerous video and audio files. While the videos load perfectly on Chrome, Firefox, and IE, they do not load on Safari for Windows. Here's a snippet of the code: <video controls="controls" type ...

Utilizing Discord.js to Transfer Users Between Voice Channels

Does anyone know the most updated method for creating a discord js bot that can move users to different voice channels? I've been encountering errors with the solutions I found online. Currently, I'm manually setting it to a specific channel for ...

A guide to exporting a PDF in A4 size landscape mode with jspdf

As a novice in UI development, I am currently trying to export HTML content to PDF using the JSPDF library. However, I have encountered difficulties in generating the PDF in A4 size landscape mode. The HTML code includes data with charts (canvasjs/chartjs) ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

Incorporate fresh data into dropdown options upon selection using Vue3

Can anyone assist me with populating specific input fields on a form using Vue 3? Currently, when a user selects an option from my dropdown menu, all inputs are displayed instead of just the relevant ones. Below is the select dropdown code: <select v- ...

Can anyone offer me advice on troubleshooting a failed Capifony deployment caused by a time out during the assetic:dump process?

$ cap deploy Unfortunately, the deployment process is failing and I am receiving the following error message: * executing "cd /var/www/site/prod/releases/20120831164520 && php app/console assetic:dump web --env=prod --no-debug" servers: ["site ...

Aggregate X and Y values based on a key in a scatter plot using dc.js

Here is a glimpse of my dataset: var items = [ {name: "X", duration: 1, quantity: 2}, {name: "X", duration: 2, quantity: 1}, {name: "Y", duration: 1, quantity: 4}, {name: "X", duration: 3, quantity: 1 ...

Even in the face of errors, Selenium with Node.js continues to run seamlessly. The challenge arises specifically with the 107.xx version of the Chrome browser and Chrome driver

Currently, I am employed in a project involving NODE JS (javascript) with selenium webdriver. Package.json- “chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7. ...

Creating a custom color palette with Material UI using ThemeProvider

Attempting to set a custom color for a Button using createMuiTheme and ThemeProvider has been successful with the primary and secondary palettes. However, when trying to utilize an alternate color such as "info", it does not seem to work as expected: http ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Exploring jQuery functionality through data attributes

I'm having trouble implementing the search functionality using the data-find attribute. Currently, my function is simply matching the input string with any text inside the container. You can test this by adding more words to the HTML and then enterin ...

Protecting website pages on both the admin and user side in Next.js 14 to ensure maximum security

I'm currently using nextjs 14 and I am working on developing a website similar to a property app. It will have an admin dashboard and a user side. How can I ensure the security of both the admin and user sides, and what should my folder structure look ...