Search code examples
databasemongodbprisma

Prisma - Set property's type as array of enum


This is my model:

model ExampleModel {
  id   String @id @default(auto()) @map("_id") @db.ObjectId
  name String @unique
  foo  ...
}

enum Tags {
  TagA
  TagB
  TagC
}

I want to set the type of foo as an array of Tags, (an example value of foo would be ['TagA', 'TagC']. How do I do that? Using foo Tags[] sets the type of foo as "TagA"[] | undefined


Solution

  • If you want to make foo an array of Tags enum, you can indeed use foo Tags[]. However, the type "TagA[] | undefined" means that foo can be an array of TagA, or it can be undefined (not set). This is the expected type when you define an array field in Prisma, but it is not required and does not have a default value.

    If you want foo to always have a value (i.e., it can never be undefined), you can make it a required field by appending the @default directive with an empty array as a default value, like so:

    model ExampleModel {
      id   String @id @default(auto()) @map("_id") @db.ObjectId
      name String @unique
      foo  Tags[] @default([])
    }
    
    enum Tags {
      TagA
      TagB
      TagC
    }
    
    

    In this revised schema, foo is a required field that defaults to an empty array if no value is provided. It will always be an array of Tags, never undefined.