Ayden's journal

Excluding fields

기본적으로 prisma client는 모델의 모든 필드를 반환한다. select를 사용하면 필드의 일부만을 반환하도록 할 수 있지만, 수십 개가 넘는 필드에서 두 개의 필드만 제외하려면 omit을 사용하는 게 낫다. select와 달리 omit을 통한 필드 제외하기는 prisma 5.16 버전부터 previewFeatures를 통해 켜주어야 한다.

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["omitApi"]
}

 

 

Excluding a field globally using omit

만약 어떤 필드를 전역적으로 제외하고 싶다면 PrismaClient 수준에서 omit을 설정해야 한다.

const prisma = new PrismaClient({
  omit: {
    user: {
      password: true
    }
  }
})

// The password field is excluded in all queries, including this one
const user = await prisma.user.findUnique({ where: { id: 1 } })

전역적으로 제외되었다고 해도 필요한 경우에는 select나 omit:false를 사용하여 PrismaClient의 설정을 덮어쓸 수 있다.

const user = await prisma.user.findUnique({
  select: {
    firstName: true,
    lastName: true,
    password: true // The password field is now selected.
  },
  where: {
    id: 1
  }
})

const user = await prisma.user.findUnique({
  omit: { password: false }
  where: {
    id: 1
  }
})

 

Excluding a field locally using omit

필드 제외를 각 쿼리 수준으로 제한하는 것도 가능하다. 또한 omit으로는 하나 이상의 필드를 원하는 만큼 제외할 수 있다.

const prisma = new PrismaClient()

// The password and email field is excluded only in this query
const user = await prisma.user.findUnique({
  omit: {
    email: true,
    password: true,
  },
  where: { 
    id: 1 
  } 
})

 

 

 

공식문서에 따르면 비밀번호와 같은 민감한 필드는 전역적으로 omit하는 것이 좋고, 대부분의 경우에는 로컬에서 제외하는 것을 추천하는 듯하다.

블로그의 정보

Ayden's journal

Beard Weard Ayden

활동하기