Excluding fields

By default Prisma Client returns all fields from a model. You can use select to narrow the result set, but that can be unwieldy if you have a large model and you only want to exclude one or two fields.

Prisma Client doesn't have a native way of excluding fields yet, but it's easy to create a function that you can use to exclude certain fields in a type-safe way.

Excluding the password field

The following is a type-safe exclude function returns a user without the password field.

TypeScript
JavaScript
// Exclude keys from user
function exclude<User, Key extends keyof User>(
user: User,
keys: Key[]
): Omit<User, Key> {
return Object.fromEntries(
Object.entries(user).filter(([key]) => !keys.includes(key))
)
}
function main() {
const user = await prisma.user.findUnique({ where: 1 })
const userWithoutPassword = exclude(user, ['password'])
}

In the TypeScript example, we've provided two generics: User and Key. The Key generic is defined as the keys of a User (e.g. email, password, firstName, etc.).

These generics flow through the logic, returning a User that omits the list of Keys provided.

Going further

  • Learn how you can move the exclude function into a custom model.
  • Instead of excluding fields, another option is to obfuscate the field.
  • There's an outstanding feature request to add exclude support natively in Prisma Client. If you'd like to see that happen, make sure to upvote that issue and share your use case!
Edit this page on GitHub