简体   繁体   中英

How can I UPDATE fields separately with Prisma?

I have an object called Post with fields that I need to be able to UPDATE separately. For example, the object will have three fields: title content summary .

Use case

I can create a post object and save it in my DB by filling in the field title , and the other fields with empty strings. The idea is to be able to go to the individual post page via it's id, and then update the other fields as and when i need to.

On my page I have this code 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);
            }
        };

In my API route, I have the following:

    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'})
        }

I can't get this to work, no mutation happens when I have it this way, ie

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

But when I have it this way

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

If I update just one of these, I get a mutation, but it updates all the 3 fields with the same value.

How can I just update one field at a time?

Assuming that title is a string. If you are passing

body: JSON.stringify(title)

in the API then req.body will be a string. And when you are doing

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

then this string will be stored in all three variables. And you thus all three attributes of the post will be updated with the same value.

Typically you would pass something like:

body: {
  title: "new title"
}

in the API.

Then the body would be that object. And if you do

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

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

You can then use these values to update your database accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM