🌐
GitHub
github.com › prisma › prisma › issues › 22584
Permit falseable fields when using `select` or querying · Issue #22584 · prisma/prisma
January 7, 2024 - If a false field is informed we look to see if theres any other field with true. If only false fields are informed, we do a select(*) retrieving all data EXCEPTING the false values informed.
Author   prisma
Discussions

Select everything except some fields
prisma.user.findMany({ select: {'*': true, password: false}, orderBy: { createdAt: 'desc' } }) More on github.com
🌐 github.com
1
April 20, 2022
Passing non-literal boolean type to include/select does not correctly update the output type
Prisma fails to modify the output type of included/selected items as possibly undefined when the type enabling the include/select is boolean (not a boolean literal- true or false) More on github.com
🌐 github.com
0
March 25, 2023
node.js - NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records? - Stack Overflow
I'm trying to fetch data records from a Postgres database in NestJS (Node.JS environment). I'm using Prisma as my Object Relational Mapper (ORM) in TypeScript. I'm having trouble choosing which que... More on stackoverflow.com
🌐 stackoverflow.com
🔍 Setting Default Select Value for Prisma Fields
I have certain fields in my Prisma model, such as createdAt, updatedAt, and deletedAt. When querying the database using Prisma, I want to avoid retrieving data for these fields unless explicitly st... More on github.com
🌐 github.com
1
1
July 23, 2023
🌐
Prisma
prisma.io › home › select fields › select fields › select fields › select fields
Select fields | Prisma Documentation
Learn how to exclude fields from Prisma Client results with the omit option. Return the default fieldsSelect specific fieldsReturn nested objects by selecting relation fieldsNest selectionsOmit fields instead of selecting everything manuallyRelated pages
🌐
GitHub
github.com › prisma › prisma › issues › 12894
Select everything except some fields · Issue #12894 · prisma/prisma
April 20, 2022 - prisma.user.findMany({ select: {'*': true, password: false}, orderBy: { createdAt: 'desc' } }) prisma.user.findMany({ deSelect: {password: true}, orderBy: { createdAt: 'desc' } }) // OR prisma.user.findMany({ except: {password: true}, // to ...
Author   prisma
🌐
Prisma
prisma.io › home › excluding fields › excluding fields › excluding fields › excluding fields
Excluding fields | Prisma Documentation
const user = await prisma.user.findUnique({ where: { id: 1 }, omit: { password: true, }, }); ... Use select when you want to return only a small subset of fields.
🌐
GitHub
github.com › prisma › prisma › issues › 18499
Passing non-literal boolean type to include/select does not correctly update the output type · Issue #18499 · prisma/prisma
March 25, 2023 - Prisma fails to modify the output type of included/selected items as possibly undefined when the type enabling the include/select is boolean (not a boolean literal- true or false)
Author   prisma
Find elsewhere
Top answer
1 of 1
25

It's explained in the documentations of Select fields and Relation Queries That include and select have different usage:

By default, when a query returns records [..], the result includes the default selection set:

All scalar fields defined in the Prisma schema [..and] None of the relations

To change this behavior, you can use:

(1) Select:

allows you to either return a limited subset of fields instead of all fields:

const getUser: object | null = await prisma.user.findUnique({
  where: {
    id: 22,
  },
  select: {
    email: true,
    name: true,
  },
})

// Result
{
  name: "Alice",
  email: "[email protected]",
}

or include relations and select relation fields (nested usage):

const users = await prisma.user.findMany({
  select: {
    name: true,
    posts: {
      select: {
        title: true,
      },
    },
  },
})

(2) Include:

allows you to return some or all relation fields (which are not returned by default as mentioned before):

const getPosts = await prisma.post.findMany({
  where: {
    title: {
      contains: 'cookies',
    },
  },
  include: {
    author: true, // Return all fields
  },
})

// Result:
;[
  {
    id: 17,
    title: 'How to make cookies',
    published: true,
    authorId: 16,
    comments: null,
    views: 0,
    likes: 0,
    author: {
      id: 16,
      name: null,
      email: '[email protected]',
      profileViews: 0,
      role: 'USER',
      coinflips: [],
    },
  },
  {
    id: 21,
    title: 'How to make cookies',
    published: true,
    authorId: 19,
    comments: null,
    views: 0,
    likes: 0,
    author: {
      id: 19,
      name: null,
      email: '[email protected]',
      profileViews: 0,
      role: 'USER',
      coinflips: [],
    },
  },
]

(3) Select within Include:

Finally, you can use Select within Include, to return a subset of the relation fields.

const users = await prisma.user.findMany({
  // Returns all user fields
  include: {
    posts: {
      select: {
        title: true,
      },
    },
  },
})
🌐
GitHub
github.com › prisma › prisma › discussions › 20346
🔍 Setting Default Select Value for Prisma Fields · prisma/prisma · Discussion #20346
July 23, 2023 - The select modifier allows you to specify which fields you want to retrieve from the database. By default, if you do not include the select modifier, Prisma will retrieve all fields defined in the model.
Author   prisma
🌐
GitHub
github.com › prisma › prisma › issues › 4246
Add option to skip unnecessary `SELECT` after `create()` · Issue #4246 · prisma/prisma
November 12, 2020 - prisma:query COMMIT prisma:query BEGIN prisma:query INSERT INTO "public"."log" ("smth") VALUES ($1) RETURNING "public"."log"."uuid" prisma:query SELECT "public"."log"."uuid" FROM "public"."log" WHERE "public"."log"."uuid" = $1 LIMIT $2 OFFSET $3 prisma:query COMMIT · Add option to skip select after insert or update (in case of operation fail error is thrown by default) db.log .create({ data: { smth: 1 }, select: false }) Logs: prisma:query COMMIT prisma:query BEGIN prisma:query INSERT INTO "public"."log" ("smth") VALUES ($1)" prisma:query COMMIT ·
Author   prisma
🌐
Prisma Client Python
prisma-client-py.readthedocs.io › en › stable › reference › operations
Query Operations - Prisma Client Python - Read the Docs
In lieu of more extensive documentation, this page documents query operations on the prisma client such as creating, finding, updating and deleting records.
🌐
GitHub
github.com › prisma › prisma › issues › 6615
When `boolean` (rather than explicit `true` or `false`) values are used in `select` or `include`, infer result type as an optional field · Issue #6615 · prisma/prisma
April 16, 2021 - When boolean (rather than explicit true or false) values are used in select or include, infer result type as an optional field#6615 ... I have a model in prisma that looks conceptually like this (simplifying for the sake of this report):
Author   prisma
🌐
Prisma
prisma.io › home › type safety overview › type safety overview › type safety overview
Type safety | Prisma Documentation
Its object properties match those that are supported by select statements according to the model. The first tab below shows the UserSelect generated type and how each property on the object has a type annotation. The second tab shows the original schema from which the type was generated. ... type Prisma.UserSelect = { id?: boolean | undefined; email?: boolean | undefined; name?: boolean | undefined; posts?: boolean | Prisma.PostFindManyArgs | undefined; profile?: boolean | Prisma.ProfileArgs | undefined; }
🌐
Medium
medium.com › @aliammariraq › prisma-exclude-with-typesafety-8484ea6d0c42
Prisma Exclude With TypeSafety. Prisma, a powerful Node.js/TypeScript… | by Ali Ammar | Medium
June 24, 2023 - When we need to exclude a specific ... in Prisma, the conventional approach requires us to explicitly list all the desired fields and omit the unwanted one. This can become cumbersome and error-prone, especially when dealing with models that have numerous fields. Every time a new field is added to the model, the select object must be updated accordingly · // we do not need password , so we must select all field with true valuse and either do not select password or pass it with false value ...
🌐
Stack Overflow
stackoverflow.com › questions › 57306680 › how-to-filter-a-boolean-in-prisma
How to filter a boolean in prisma
{ OR: [ { name_contains: args.filter }, { email_contains: args.filter }, { phone_contains: args.filter }, { active: args.filter }, ], } : {} return await context.prisma.users({ where, }) } ... In theory, this would work if I simply passed 'TRUE' or 'FALSE' as my filter argument but this obviously doesn't work as more booleans are added to the User type, and also is not very clear.
🌐
GitHub
github.com › prisma › prisma › issues › 5575
Query produces `WHERE` clause with 1=0 as condition · Issue #5575 · prisma/prisma
February 10, 2021 - import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient({ log: ['query'], }) // A `main` function so that we can use async/await async function main() { const searchString: string | null = null const posts = await prisma.post.findMany({ where: { OR: [ { title: { contains: searchString || undefined } }, { content: { contains: searchString || undefined } }, ], }, }) console.log(posts) } main() .catch((e) => { console.error(e) process.exit(1) }) .finally(async () => { await prisma.$disconnect() }) ... SELECT `dev`.`Post`.`id`, `dev`.`Post`.`title`, `dev`.`Post`.`content`, `dev`.`Post`.`published`, `dev`.`Post`.`authorId` FROM `dev`.`Post` WHERE 1=0 LIMIT ? OFFSET ? As far as I understand, the 1=0 condition in the WHERE clause means that there will never be any records returned because the WHERE clause will always be evaluated to false.
Author   prisma
Top answer
1 of 12
9

I've been wondering about how to implement this as well, and bafflingly the issues linked in @Ryan's post are over two years old, and still unresolved. I came up with a temporary workaround, which is to implement a middleware function for the Prisma client which removes the password field manually after each call.

import { PrismaClient } from '@prisma/client'

async function excludePasswordMiddleware(params, next) {
  const result = await next(params)
  if (params?.model === 'User' && params?.args?.select?.password !== true) {
    delete result.password
  }
  return result
}

const prisma = new PrismaClient()
prisma.$use(excludePasswordMiddlware)

This will check if the model being queried is a User, and it will not delete the field if you explicitly include the password using a select query. This should allow you to still get the password when needed, like when you need to authenticate a user who is signing in:

async validateUser(email: string, password: string) {
  const user = await this.prisma.user.findUnique({
    where: { email },
    select: {
      emailVerified: true,
      password: true,
    },
  })
  // Continue to validate user, compare passwords, etc.
  return isValid
}
2 of 12
6

The only legit way is adding column: true to the columns you want to include. There are requests for excluding columns here so it would be great if you could add a 👍 to the request relevant to you so that we can look at the priority.

https://github.com/prisma/prisma/issues/5042 https://github.com/prisma/prisma/issues/7380 https://github.com/prisma/prisma/issues/3796

🌐
PalJS
paljs.com › plugins › select
GraphQL Enhancement Plugins | Packages | PalJS
Without DMMF: PrismaSelect still works — it generates select objects but skips field validation.
🌐
Reddit
reddit.com › r/node › prisma select argument not getting correct type hints when using a proxy function to access findunique
r/node on Reddit: Prisma select argument not getting correct type hints when using a proxy function to access findUnique
July 23, 2023 - } } } })).id) let relations = await user.getRelations({ posts: false, messages: true }) // let relations: { // messages: (GetResult<{ // id: number; // content: string; // authorID: number; // }, unknown> & {})[]; // } | null // Desired result let relations2 = await client.user.findUnique({ where: { id: user.id }, select: { posts: false, messages: true } }) // let relations2: { // messages: (GetResult<{ // id: number; // content: string; // authorID: number; // }, unknown> & {})[]; // } | null console.log("Relation ->", relations, "Relation2 ->", relations2) })(); ... Nobody's responded to this post yet. Add your thoughts and get the conversation going. How to make type safe a function that receives a prisma.[modelName] ?
🌐
Prisma
prisma.io › blog › introducing-global-omit-for-model-fields-in-prisma-orm-5-16-0
Prisma ORM 5.16.0 allows global or local omitted fields in Prisma Client
June 25, 2024 - const usersWithoutPasswords = await prisma.user.findMany({ omit: { password: true }, }); Now you have the flexibility to omit a field globally and only select it in specific circumstances, or vice versa!