From the course: Master Next.js by Building Scalable Apps with Routing, Databases, and Performance

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

The upsert() method

The upsert() method

Finally, we will have a look at the upsert method which is a combination of insert and the update methods. This method can be used to insert or update data. For example, I have the following records in a table and let's say I want that the product name banana should have price 30, then we can use the update method. But what if I am not sure if the banana record exists or not? And I want that if banana doesn't exist, then it should add a record with name banana and price 30. That's where we use the absurd method. It will edit the record if a row is matched, else it will insert a new row. The syntax is like this. You call the method and pass the object as argument. Then it will take in the condition to search the row and the update property to enter the updated fields. And if there is no field matching to the condition, then the create property will be used in which you define the new field colon value pairs. Let's practically try it. I'll use the edit product code for this. Alright…

Contents