user3226932
user3226932

Reputation: 2232

check if record exists using prisma graphql apollo

trying to check if a record exists in a table in Postgres using Prisma, but seems like I can only query the id field, but not any other fields like name and location, which gives a compiler error

model schema.prisma

model place {
  id             Int              @id @default(dbgenerated("nextval('place_id_seq'::regclass)"))
  name           String
  location       String @unique
}

generated type

export type Place = {
  __typename?: 'Place';
  name?: Maybe<Scalars['String']>;
  location?: Maybe<Scalars['String']>;

};

Query resolver

let findPlace = await prisma.place.findUnique(
        {
          where: {
            name: "abc"
          }
        }
)

error

Type '{ name: string; }' is not assignable to type 'placeWhereUniqueInput'.
  Object literal may only specify known properties, and 'name' does not exist in type 'placeWhereUniqueInput'.ts(2322)
index.d.ts(1361, 5): The expected type comes from property 'where' which is declared here on type '{ select?: placeSelect | null | undefined; include?: placeInclude | null | undefined; rejectOnNotFound?: RejectOnNotFound | undefined; where: placeWhereUniqueInput; }'

what's missing here to make this work?

Upvotes: 3

Views: 17937

Answers (2)

user3817008
user3817008

Reputation: 893

findUnique only works for unique fields. You shouldn't use count either as it unnecessarily goes through the whole table.

The better approach is to use findFirst, which is basically a LIMIT 1 on the database, so the database can stop searching for more results after the first hit.

const exists = !!await prisma.place.findFirst(
  {
    where: {
      name: "abc"
    }
  }
);

I'm using the !! to cast the object to a boolean.

Upvotes: 8

Tasin Ishmam
Tasin Ishmam

Reputation: 7198

Prisma won't accept findUnique queries where the condition only contains non unique fields (in this case, name). If you just need to find whether a place record with appropriate condition exists or not, you can use the count API.

let placeCount = await prisma.place.count(
        {
          where: {
            name: "abc"
          }
        }
)
// placeCount == 0 implies does not exist

Upvotes: 13

Related Questions