Search code examples
databasepostgresqlormprisma

Prisma: Is it possible to have a field on a model be an array of objects without any relation?


I have a field on my user model called favorites. I want this to be an array of objects. I cannot set the field to be an array without some kind of relation or defining it, but there is no way to define it with an object. I also cannot use types since I am using a PostgreSQL DB. Is there any way I can have an array as a field that takes in objects without that field having any relation to another model?

An example of some dummy data in the favorites field

[
  { id: 1,
    title: 'blah'
  },
  
  { id: 2,
    title: 'ok'
  },
 
]

my schema:

model User {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @updatedAt
  email     String     @unique
  firstName String
  lastName  String
  password  String
  playlists Playlist[]
  favorites Song[]
}

I currently have favorites related to a Song model which I do not need. I just want favorites to be an array of objects that I store with no relation. Something like:

model User {
  favorites {}[]
}


Solution

  • One way to do this would be using the Json type in the Prisma schema:

    model User {
      favorites Json
    }
    

    The main drawback is that this is currently not typed (until Prisma supports typed Json fields), so you won't get any autocompletion or type-safety from the TS compiler.

    If you want to have the type-safety, you'll need to model it as a relation as of now (or use MongoDB where embedded documents are already supported via the type keyword).