简体   繁体   中英

prisma findUnique where takes only one unique argument

I ran into an issue where I need to check if a user exists by his username and email since both are unique fields in the database, but I got an error. Argument where of type UserWhereUniqueInput needs exactly one argument, but you provided username and email. Please choose one. so, is there a way to execute this query just once?. instead of running one for each like the following

const user = await prisma.user.findUnique({
        where: {
          username,
          email,
        },
      });

and not like this

const user = await prisma.user.findUnique({
        where: {
          username,
        },
      });

const user = await prisma.user.findUnique({
        where: {
          email,
        },
      });

I am not entirely certain, but prisma returns a JS object... So perhaps a query like this should work:

const query = await prisma.user.findUnique({
        where: {
          user: user.username
        },
       select: {
         user: true,
         email: true
      }
      });

I believe this should work, but it still only finds by one unique. I am not sure exactly why you would select user + email as both unique, as I would assume that one is tied to the other anyhow.

I would take a look over here for further answers if my solution was not able to work: https://www.prisma.io/docs/concepts/components/prisma-client/crud#findfirst

Logically speaking, the email is a unique field (there won't be the same email shared by two persons). The username field isn't unique (multiple user's with same name).
This below code alone is enough to fetch that unique user.

const user = await prisma.user.findUnique({
        where: {
          email
        },
      });

But let's just assume that email or username alone isn't unique and a combination of email and username is unique.

Modify your schema shown below

model user {
  username : String
  email    : String
  @@unique([username, email])
}

You can now query by unique email and username without providing multiple where arguments

   const user = await prisma.findUnique({
        where: {
          username_email : { username, email },
        },
      });

References:

const users = await prisma.user.findMany({
       where: {
        OR: [
          {username},
          {email}
        ]
      }
  });
 if (users.length !== 0) {...}

if you are looking for a unique value that would bring you a single result you can use findFirst as well. which would give you Object instead of Array. findMany returns an Array even though you are looking for a unique value.

const users = await prisma.user.findFirst({
 where: {OR: [{username},{email}]}
});

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