How to increment a column of a prisma table by one in nodejs?

June 2024 ยท 1 minute read

It is possible on my javascript application to like posts. And I created an nb_likes column of integer type in the prisma table containing the different posts of the application. I would like when a like is added to a post, the value of the nb_likes column is incremented by 1. So I wrote the following code:

await db.post.update({ . . . nb_likes : { increment, } }, }); 

I expected the value of the nb_likes column to be implicitly increased by 1 but the increment keyword is not recognized. I searched the internet, but couldn't find anything about it. Thanks !

1 Answer

With Prisma, you can perform atomic operations for Int and Float fields.

increment: x: Adds x to the current value

decrement: x: Subtracts x from the current value

multiply: x: Multiplies the current value by x

divide: x: Divides the current value by x

set: x: Sets the value to x (equivalent to data: { age: 18 })

You can learn more from the docs

An example is shown

const updatePosts = await prisma.post.updateMany({ data: { views: { increment: 1, }, likes: { increment: 1, }, }, }) 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmxsZmqGd4I%3D