【问题标题】:Check if data record already exists (if no = create | if yes = do nothing)检查数据记录是否已经存在(如果没有=创建|如果是=什么都不做)
【发布时间】:2022-12-14 01:48:27
【问题描述】:

我目前开始使用 prisma.schema 和 mongodb

我有两个集合,它们在 Artwork 和 Like 之间具有字段关系。

首先被称为“艺术品”

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[]
}

第二个叫“赞”

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
}

如果有人喜欢我的作品,我会在喜欢收藏中创建以下记录

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

现在我想防止在集合表中创建完全相同的记录。

如果数据集像这样 1:1 存在,有没有比预先发送查询更好的方法?

【问题讨论】:

    标签: database mongodb prisma


    【解决方案1】:

    您可以在 userIdartworkId 上创建一个组合的唯一索引,以仅允许用户点赞或这样的艺术品:

    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])
    }
    

    这是创建Compound Unique Index的参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2011-05-12
      • 1970-01-01
      相关资源
      最近更新 更多