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> {
for (let key of keys) {
delete user[key]
}
return user
}
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.
  • There's an outstanding feature request to add exclude support natively to the 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