Home > Software engineering >  how to create a optional list field in prisma
how to create a optional list field in prisma

Time:01-13

I am creating a basic crud api with nodejs and prisma. My Schema is as follows:

generator client {
       provider = "prisma-client-js"
}

datasource db {
       provider          = "postgresql"
       url               = env("DATABASE_URL")
       shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

  

model Category {
       id          String    @unique @default(cuid())
       title       String
       description String
       products    Product[]
}

model Product {
  id          String    @unique @default(cuid())
  title       String
  description String
  price       Float
  createdAt   DateTime  @default(now())
  updatedAt   DateTime?

  category   Category? @relation(fields: [categoryId],  references: [id])
  categoryId String?
}

I am trying to make the products field in the Category model optional. But Prisma doesn't allow that. But I want my users to create a category even without creating a post or vice-versa. How can I get around this?

CodePudding user response:

According to the Prisma documentation, lists cannot be optional: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#remarks-5

However, the products field not being optional does not mean that it cannot be an empty when a new Category is created:

await prisma.category.create({
  data: {
    title: 'books',
    description: 'books',
    products: {},
  }
})

Then you can create or connect the product later:

await prisma.category.update({
  where: {
    id: "category-id"
  },
  data: {
    products: {
      connect: {
        id: "product-id"
      }
    }
  }
})
  •  Tags:  
  • Related