Home > Net >  Check if data record already exists (if no = create | if yes = do nothing)
Check if data record already exists (if no = create | if yes = do nothing)

Time:12-14

i currently started with prisma.schema and mongodb

I have two collections with a field relations between Artwork and Like.

first is called "Artwork"

model Artwork {
  id String @id @default(auto()) @map("_id") @db.ObjectId

  name        String?

  mediaFile MediaFile[]

  userId String? @db.ObjectId
  user   User?   @relation(fields: [userId], references: [id])

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  
  like      Like[]
}

second is called "Like"

model Like {
  id String @id @default(auto()) @map("_id") @db.ObjectId

  userId String? @db.ObjectId
  user   User?   @relation(fields: [userId], references: [id])

  artwork   Artwork? @relation(fields: [artworkId], references: [id])
  artworkId String?  @db.ObjectId

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

If someone like a artwork i will create the following record in Like collection

{
  userId: 'string',
  artworkId: 'string',
}

Now i want to prevent, to create the exact same record in the collections table.

Is there a better way than to send a query beforehand if the dataset exists 1:1 like this?

CodePudding user response:

You can create a combined unique index on userId and artworkId to only allow a single Like by a user or an artwork like this:

model Like {
  id String @id @default(auto()) @map("_id") @db.ObjectId

  userId String? @db.ObjectId
  user   User?   @relation(fields: [userId], references: [id])

  artwork   Artwork? @relation(fields: [artworkId], references: [id])
  artworkId String?  @db.ObjectId
  

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@unique([userId, artworkId])
}

Here's a reference for creating Compound Unique Index.

  • Related