The field in where clause of the upsert query should be unique.

In this case, the email field is not unique due to which you are getting this error.

Updating schema file by adding @unique attribute to the email field will solve the issue.

model prismaUser {
  id           Int    @id @default(autoincrement())
  name         String @db.VarChar(255)
  email        String @unique @db.VarChar(255)
  profileViews Int
  role         String @db.VarChar(255)
}
Answer from Nurul Sundarani on Stack Overflow
🌐
GitHub
github.com › prisma › prisma › issues › 22778
`upsert()` results in P2002 · Issue #22778 · prisma/prisma
January 23, 2024 - Bug description Calling upsert while another record is created results in P2002 (Unique constraint failed). How to reproduce We are sending SMS messages via Twilio and saving the response data to o...
Author   prisma
Discussions

Invalid `prisma.***.upsert()` invocation in ...
Bug description Keep getting invalid invocation when using upsert How to reproduce Expected behavior No response Prisma information model Settings { sub String @id darkMode Boolean } const { sub } ... More on github.com
🌐 github.com
5
March 2, 2023
upsert error when undefined field
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB - prisma/prisma More on github.com
🌐 github.com
6
May 16, 2022
Error with multiple upsert in $transaction
Bug description When I execute query, these two errors alternately appeared. One is ConnectorError and the other is Unique constraint error. Second error is kind of strange, because I chose this ap... More on github.com
🌐 github.com
7
January 10, 2022
Incorrect logging for `upsert` error with `Infinity`
When I use upsert with an invalid payload, I am getting the wrong error message. The problem is clearly that listingPrice is being set to Infinity, but the error is reporting that marketplaceIntegration is missing, even though it isn't. ... const inventoryItemData: Prisma.InventoryItemUnch... More on github.com
🌐 github.com
3
June 26, 2023
🌐
Prisma
prisma.io › home › crud › crud › crud › crud
CRUD (Reference) | Prisma Documentation
To emulate findOrCreate(), use upsert() with an empty update parameter. await prisma.post.updateMany({ data: { views: { increment: 1 }, likes: { increment: 1 }, }, }); See Relation queries for connecting and disconnecting related records. The following query uses delete() to delete a single User record: const deleteUser = await prisma.user.delete({ where: { email: "bert@prisma.io", }, }); Attempting to delete a user with one or more posts result in an error...
🌐
GitHub
github.com › prisma › prisma › issues › 18183
Invalid `prisma.***.upsert()` invocation in ... · Issue #18183 · prisma/prisma
March 2, 2023 - Keep getting invalid invocation when using upsert · No response · model Settings { sub String @id darkMode Boolean } const { sub } = res.locals.user as User, [settings] = await prisma.$transaction([ prisma.settings.upsert({ where: { sub }, update: {}, create: { sub, darkMode: false }, }), ]); OS: Ubuntu 20.04 LTS ·
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 13385
upsert error when undefined field · Issue #13385 · prisma ...
May 16, 2022 - prisma[table].upsert() error when receive undefined value, example: prisma.post.upsert({ where: {id}, create: {name: 'john', age: 20}, update: {name: 'jean', age: undefined} // will error }) {,…} error: {clientVersion: "3.13.0"} message: "something went wrong - Error: Invalid `prisma.skill.upsert()` invocation: { where: { id: 'cl3882yhh0115llgqp44yzt9f' }, update: { imagePath: '/public/uploads/', imageName: undefined, name: 'Reed Daniel', url: 'https://www.duhoxykitobef.ws' }, create: { imagePath: '/public/uploads/', + imageName: String, name: 'Reed Daniel', url: 'https://www.duhoxykitobef.ws', userId: 'cl37fhaqa1208vq3ttucls59v', ?
Author   prisma
🌐
Prisma
prisma.io › home › prisma client api › prisma client api › prisma client api
Prisma Client API | Prisma Documentation
Handle the P2002 error in your application code. When it occurs, retry the upsert operation to update the row. Where possible, Prisma Client hands over an upsert query to the database.
🌐
GitHub
github.com › prisma › prisma › issues › 11038
Error with multiple upsert in $transaction · Issue #11038 · prisma/prisma
January 10, 2022 - Error: Invalid `prisma.tag.upsert()` invocation: Error occurred during query execution: ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Server(ServerError { code: 1213, message: "vttablet: rpc error: code = Aborted desc = (errno 1213) (sqlstate 40001) (CallerID: unsecure_grpc_client): Sql: \"insert into Tag(id, createdAt, updatedAt, `name`, userId) values (:v1, :v2, :v3, :v4, :v5)\", BindVars: {}", state: "40001" })) }) at cb (/Users/yujonglee/dev/taggy.cloud/node_modules/@prisma/client/runtime/index.js:38692:17) at async Promise.all (index 0) at async createFile (/Us
Author   prisma
🌐
GitHub
github.com › prisma › prisma › discussions › 16882
Using upsert · prisma/prisma · Discussion #16882
There was an error while loading. Please reload this page. ... prisma.server.upsert({ where: { id: input.id ??
Author   prisma
Find elsewhere
🌐
GitHub
github.com › prisma › prisma › issues › 19966
Incorrect logging for `upsert` error with `Infinity` · Issue #19966 · prisma/prisma
June 26, 2023 - When I use upsert with an invalid payload, I am getting the wrong error message. The problem is clearly that listingPrice is being set to Infinity, but the error is reporting that marketplaceIntegration is missing, even though it isn't. ... const inventoryItemData: Prisma.InventoryItemUncheckedCreateInput | Prisma.InventoryItemUpdateInput = { asin, dead: deadProduct, fnsku, fulfillment: 'FBA', groupId: fnsku, listingCurrency: MarketplaceUtils.getCurrencyCode(marketplace), listingPrice: Number.isFinite(calculatedPrice) ?
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 5233
`upsert()` `where` is defined as `number | undefined` but does not allow `undefined` to not select anything · Issue #5233 · prisma/prisma
January 21, 2021 - There was an error while loading. Please reload this page. ... upsert() where is defined as number | undefined but does not allow undefined to not select anything#5233 ... tech/typescriptIssue for tech TypeScript.Issue for tech TypeScript.topic: client typesTypes in Prisma ClientTypes in Prisma Clienttopic: undefinedtopic: upsertnested upsertnested upserttopic: upsert()
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 9751
Concurrent relation upserts conflict · Issue #9751 · prisma/prisma
October 13, 2021 - Bug description Running multiple upserts concurrently and receiving the error: PrismaClientKnownRequestError3 [PrismaClientKnownRequestError]: Invalid `prisma.post.upsert()` invocation: Unique constraint failed on the fields: (`name`,`ty...
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 21853
`upsert()` fails on unique key when being used as "`findOrCreate`" with empty `update` field · Issue #21853 · prisma/prisma
November 8, 2023 - Bug description Prisma does not seems to hand off upsert correctly when the update field is left empty. I instead get a Unique constraint failed on the fields (Username, password) database error. How to reproduce When using a compound in...
Author   prisma
🌐
Goprisma
goprisma.org › docs › walkthrough › upsert
Upsert records – Prisma Client Go
October 22, 2024 - post, err := client.Post.UpsertOne( // query db.Post.ID.Equals("upsert"), ).Create( // set these fields if document doesn't exist already db.Post.Published.Set(true), db.Post.Title.Set("title"), db.Post.ID.Set("upsert"), ).Update( // update these fields if document already exists db.Post.Title.Set("new-title"), db.Post.Views.Increment(1), ).Exec(ctx)
🌐
GitHub
github.com › prisma › prisma › issues › 26082
Upsert in transaction not working · Issue #26082 · prisma/prisma
January 13, 2025 - Bug description I'm trying to upsert inside of a $transaction. One of the fields isn't populating and I cannot figure out why. Although frustrating, that's not why I'm reporting a bug. In my console, while working through the problem I g...
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 29479
Prisma Client throws P2025 error on nested update with upsert when record exists in PostgreSQL · Issue #29479 · prisma/prisma
April 16, 2026 - Bug description When performing a nested upsert inside an update operation using Prisma Client with PostgreSQL, a P2025 (Record not found) error is thrown even though the record exists in the database. Steps to reproduce: const result = ...
Author   prisma
🌐
Reddit
reddit.com › r/nextjs › prisma - is a nested upsert something that makes sense?
r/nextjs on Reddit: Prisma - is a nested upsert something that makes sense?
June 17, 2024 -

I have a question about nested upserts and if they're even possible.

I have a Prisma create that's working as expected;

An orders (table) can create an array of artwork (table), and the artwork can create an array of shirts (table).

The issue is when I want to update the shirts table through the order, similar to the create, with an upsert.

This block works as expected.

const CREATE = await prisma.orders.create({
    data: {
        artwork: {
            create: artwork.map(art => {
                return {
                    notes: art.notes,
                    shirts: {
                        create: art.shirts.map(shirt => ({
                            name: shirt.name,
                            url: shirt.url,
                        })),
                    },
                };
            })
        }
    },
});

This block works to upsert the artwork, but fails when trying to upsert the shirts.

const UPDATE = await prisma.orders.create({
    data: {
        artwork: {
            upsert: artwork.map(art => {

                const updatedArtworkWithShirts = {
                    notes: art.notes,
                    shirts: {
                        upsert: art.shirts.map(shirt => {
                            
                            const updatedShirt = {
                                name: shirt.name,
                                url: shirt.url,
                            };

                            return {
                                where: { id: shirt.id },
                                update: updatedShirt,
                                create: updatedShirt,
                            };
                        }),
                    },
                };

                return {
                    where: { id: art.id },
                    update: updatedArtworkWithShirts,
                    create: updatedArtworkWithShirts,
                };
            }),
        },
    }
});

The error I'm receiving is:

Unknown arg `upsert` in data.artwork.upsert.0.create.shirts.upsert for type shirtsCreateNestedManyWithoutArtworkInput. Did you mean `select`? 

Any thoughts? Am I approaching this incorrectly?

🌐
GitHub
github.com › prisma › prisma › issues › 5255
Upsert not creating all entries · Issue #5255 · prisma/prisma
January 24, 2021 - Bug description It is a little hard to describe, but I´m out of ideas. I in my application to mock some data and write them into the DB. So for some off my entities I created an array with data to insert and when I try to insert all of t...
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 20289
Incorrect Upsert Query used · Issue #20289 · prisma/prisma
July 19, 2023 - Bug description The Upsert query logged in Prisma is different from what Upsert actually does. It doesn't specify ON DUPLICATE KEY in query level. Query without duplicate key prisma:query BEGIN prisma:query SELECT `auth`.`users`.`id` FRO...
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 14868
"Unique constraint failed on the fields" when using upsert · Issue #14868 · prisma/prisma
August 17, 2022 - Bug description I was messing around with attempting to create a mutex lock using the db and thought I could do it via an upsert but it looks like the upsert can fail due to a race condition. The schema and code used to generate this err...
Author   prisma