CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 28d agoView on Hugging Face
1likes904downloads
prisma.jsonl338 linesDownload Raw Back to stackoverflow
1{"id":"stack-69857000","source":"stackoverflow","questionId":69857000,"title":"Prisma : how can I find all elements that match an id list?","tags":["typescript","next.js","prisma"],"text":"Title: Prisma : how can I find all elements that match an id list?\nTags: typescript, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using Prisma with NextJs.\n\nIn my API, I send to the back end a list of numbers that correspond to id's of objects in my database.\n\nAs an example, if I receive the list `[1, 2, 12]`, I would like to return the objects where the id is either 1, 2 or 12\n\nThis is part of a query that is more complex ( sorting / counting / ... ) but I am blocking at the first step with is to get the list of elements\n\nSo far I have this :\n\n```\nimport { PrismaClient, Prisma } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\nexport default async function handler(req, res) {\n if (req.method !== 'POST') {\n res.status(400).send({ message: 'Only POST requests allowed for this route' })\n } else {\n const { signes_id } = req.query\n const signes_array = signes_id.split(\",\").map(function(item) {\n return parseInt(item)\n })\n console.log(signes_array)\n const ret = await prisma.signe.findMany({\n where: {\n id: Number(signes_array),\n }\n })\n res.status(200).send(ret)\n }\n}\n```\n\nThis does not work as `Number` expects an int, not an array of int\n\nHow can I write the query such as it returns the needed array of objects ?\n\nAnd how can I deal with id's that do not match ?\n\n========================================\n\nCode:\n```text\nimport { PrismaClient, Prisma } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\n\nexport default async function handler(req, res) {\n    if (req.method !== 'POST') {\n        res.status(400).send({ message: 'Only POST requests allowed for this route' })\n    } else {\n        const { signes_id } = req.query\n        const signes_array = signes_id.split(\",\").map(function(item) {\n            return parseInt(item)\n        })\n        console.log(signes_array)\n        const ret = await prisma.signe.findMany({\n            where: {\n                id: Number(signes_array),\n            }\n        })\n        res.status(200).send(ret)\n    }\n}\n```\n\n```text\n[1, 2, 12]\n```\n\n```text\nNumber\n```\n\n```js\nconst ret = await prisma.signe.findMany({\n            where: {\n                id: { in: [1, 2, 12] },\n            }\n        })\n```\n\n```text\nin\n```\n\n```text\nid\n```\n\n```text\nfindMany\n```\n\n========================================\n\nComments:\n- This will filter duplicate posts and bring them back. What if you want to bring them all?\n- @nounlace just to clarify, are you asking what to do if you want duplicate records to be returned by `findMany` when you have an array of `id` fields with duplicate `id` values?\n- yup yup exactly\n- @nounlace Hey, sorry for the delay. Unfortunately, it's not possible to do that with a single Prisma query at the moment. I would suggest fetching the entries *without* duplicates and then organizing them *with* duplicates inside your application code. If you make a separate question for this and link it, I'd be happy to provide a code snippet that shows how to accomplish this.","metadata":{"transformedAt":"2026-08-18T18:33:14.811Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":108,"estimatedTokens":740}}2{"id":"stack-67796217","source":"stackoverflow","questionId":67796217,"title":"prisma - getting environment variable not found error message when running graphql query","tags":["prisma","prisma-graphql"],"text":"Title: prisma - getting environment variable not found error message when running graphql query\nTags: prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am getting this error message from prisma when I am running the GraphQL query.\n\n```\nEnvironment variable not found: DATABASE_URL.\\n --> schema.prisma:6\\n | \\n 5 | provider = \\\"postgresql\\\"\\n 6 | url = env(\\\"DATABASE_URL\\\")\\n | \\n\\nValidation Error Count: 1\",\n```\n\nAt first, I didn't have the .env file in any of my project folders, then I added it with the link to the database url, still not working.\nHere is the folder structure:\n\nhttps://i.sstatic.net/wh0wd.png\n\nThis is what I have inside my `.env` file looks like -\n\n```\nDATABASE_URL=\"postgres://postgres:mypassword@db.pqtgawtgpfhpqxpgidrn.supabase.co:5432/postgres\"\n```\n\n========================================\n\nTop Answer:\nIn my case I wanted to run Prisma Studio with NextJS that stores all environment variables in `.env.local`, so I need to load the file first.\n\n```\nnpm install -g dotenv-cli\n```\n\n```\ndotenv -e .env.local -- npx prisma studio\n```\n\nHere is a link to the official Prisma docs on how to load `.env` files manualy.\n\n========================================\n\nCode:\n```text\nEnvironment variable not found: DATABASE_URL.\\n  -->  schema.prisma:6\\n   | \\n 5 |   provider = \\\"postgresql\\\"\\n 6 |   url      = env(\\\"DATABASE_URL\\\")\\n   | \\n\\nValidation Error Count: 1\",\n```\n\n```text\nDATABASE_URL=\"postgres://postgres:mypassword@db.pqtgawtgpfhpqxpgidrn.supabase.co:5432/postgres\"\n```\n\n```text\n.env\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpm install -g dotenv-cli\n```\n\n```text\ndotenv -e .env.local -- npx prisma studio\n```\n\n```text\n.env.local\n```\n\n```text\n.env\n```\n\n```text\n{\n ...\n \"scripts\": {\n   ...\n   \"db-push:hard\": \"cp .env prisma/.env && yarn prisma db push --accept-data-loss\",\n   ...\n },\n ...\n}\n```\n\n```text\npackage.json\n```\n\n```text\n.env\n```\n\n```text\nschema.prisma\n```\n\n```text\npackage.json\n```\n\n```text\nimport { PrismaClient } from '@prisma/client/edge'\n```\n\n```text\nimport { PrismaClient } from '@prisma/client'\n```\n\n```text\nnpx prisma migrate dev --name name_of_migration_file\n```\n\n```text\nvercel pull\n```\n\n```text\n.env.development.local\n```\n\n```text\n.env\n```\n\n```text\n.env.development.local\n```\n\n```text\n.env\n```\n\n```text\nnpx prisma db pull\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpx prisma migrate\n```\n\n```text\ncp .env.local .env\n```\n\n```text\ndocker compose up\n```\n\n```text\ndocker-compose -f docker-compose.dev.yml up\n```\n\n```text\n.env.local\n```\n\n```text\n.env\n```\n\n```js\n\"scripts\": {\n    ....,\n    \"migrate:reset\": \"dotenv -e .env.local -- pnpx prisma migrate reset\",\n    \"migrate:dev\": \"dotenv -e .env.local -- pnpx prisma migrate dev\"\n  },\n```\n\n```bash\nC:\\>npx prisma generate\nLoaded Prisma config from prisma.config.ts.\n\nPrisma config detected, skipping environment variable loading. <-------- THIS\nPrisma schema loaded from prisma\\schema\n```\n\n```js\nimport type { PrismaConfig } from \"prisma\";\n\n// import your .env file\nimport \"dotenv/config\"; // <-- You need your env variables in this file for it to start working. This import worked for me in NextJS 15\n\nexport default {\n  schema: \"prisma/schema\", // <-- When using folder with multiple files. When using only one file do: \"prisma/schema.prisma\"\n} satisfies PrismaConfig;\n```\n\n```text\npackage.json\n```\n\n```text\nprisma.config.ts\n```\n\n```text\nprisma\n```\n\n```text\nprisma.config.ts\n```\n\n```text\nimport \"dotenv/config\";\n```\n\n```text\nprisma.config.ts\n```\n\n```text\nprisma.config.ts\n```\n\n```text\ndotenv\n```\n\n```text\nprisma.config.ts\n```\n\n```text\nprisma.config.ts\n```\n\n```text\n.env\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n========================================\n\nComments:\n- Prisma reads environment variables from .env using env(\"VAR_NAME\"). Node doesn’t load .env automatically, so Prisma can’t see DATABASE_URL. Adding `import \"dotenv&#47;config\"` loads .env before the app runs. This makes env(\"DATABASE_URL\") available.\n- For me it turned out that I had `DATABASE_URL=\"my value` and had forgotten the closing double-quote! So the value wasn't \"there\" because `dotenv` wasn't able to parse it correctly because of a mistake on my part.\n- If you are a next.js user, then see the answers below\n- for me, it's not working on next because I'm running the command in another folder different than the root project. It works perfectly running `npx prisma generate` in the correct path.\n- @aproximation env values don't need to be quoted\n- My issue was actually having the value quoted, I removed them and worked fine.\n- Thank you! This was super helpful I added `\"migrate\": \"dotenv -e .env.local npx prisma migrate dev\"` to the scripts in my package.json file as well.\n- Is there any better solution so we don't need to write the dotenv -e ... line again and again when we do any Prisma thing!!\n- This worked for me too. Why can't prisma get env vars from .local?\n- i found a solution: you add dotenv-cli and then add a custom script in package.json So in package.json, inside scripts i have: `\"db:push\": \"dotenv -e .env.local -- npx prisma db push\"` then i do `bun run db:push` (i guess you can use npx/other)\n- It solved my problem. I'm really curious why this happens.\n- Please use spacing and try to add code in code blocks for easy readability. I am not able to submit edit. However it looks like that you are able to solve this problem\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- The `import \"dotenv&#47;config\"` was the one that also made it worked for me. Thanks.\n- @Steven I got the same problem and i just added import \"dotenv/config\" to main.ts in my nestjs application.\n- This worked for me too, I just added this statement `import \"dotenv&#47;config\"` in `prisma.config.ts` Thanks!\n- import \"dotenv/config\" it worked. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:14.811Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":44,"totalLines":260,"estimatedTokens":1549}}3{"id":"stack-68366105","source":"stackoverflow","questionId":68366105,"title":"get full type on prisma client","tags":["prisma"],"text":"Title: get full type on prisma client\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nWhen i generate my prisma client with prisma generate, i got an index.d.ts with all types from my database.\nBut the probleme is that all type are \"single\" and there is no relations.\nWhen i query something like\n\n```\nprisma.users.findMany({\n // [...]\n include: {\n cars: {\n // [...]\n }\n }\n})\n```\n\nprisma type the response dynamically with the right type\n\n```\nusers & {\n cars: cars & {\n // [...]\n }\n}\n```\n\nSo everything work well and I have the auto completion, except if I want to pass this variable to another method, I would like to type the parameters, so I have to create my own type used as method parameter.\n\n```\ntype prismaUsers = users & {\n cars?: cars & {\n // [...]\n }\n}\n```\n\nBut I'm asking if there is a way to get the \"full\" type from prisma to avoid me to create all \"full\" types with optionals sub-elements like I did for the user example. Or maybe i'm doing wrong and there is another way to do?\n\n========================================\n\nTop Answer:\nYou can use the Prisma Validator API along with some typescript features to generate types for your query.\n\nFor the `findMany` example you mentioned\n\n```\nimport { Prisma } from '@prisma/client'\n\n// 1. Define a User type that includes the \"cars\" relation. \nconst userWithCars = Prisma.validator()({\n include: { cars: true },\n})\n\n// 2: This type will include many users and all their cars\ntype UserWithCars = Prisma.UserGetPayload[]\n```\n\nIf you simply want to automatically infer the return type of a prisma query wrapped in a function, you can use `PromiseReturnType`.\n\nFor example:\n\n```\nimport { Prisma } from '@prisma/client'\n\nasync function getUsersWithCars() {\n const users = await prisma.user.findMany({ include: { cars: true } });\n return users;\n}\n\ntype UsersWithCars = Prisma.PromiseReturnType\n```\n\nYou can read more about this in the Operating against partial structures of your model types concept guide in the Prisma docs.\n\n========================================\n\nCode:\n```js\nprisma.users.findMany({\n  // [...]\n  include: {\n    cars: {\n      // [...]\n    }\n  }\n})\n```\n\n```js\nusers & {\n  cars: cars & {\n    // [...]\n  }\n}\n```\n\n```js\ntype prismaUsers = users & {\n  cars?: cars & {\n    // [...]\n  }\n}\n```\n\n```js\nimport { PrismaClient, Prisma } from \"@prisma/client\";\n\nconst prisma = new PrismaClient();\n\ntype UserWithCars = Prisma.UserGetPayload<{\n  include: {\n    cars: true;\n  }\n}>\n\nconst usersWithCars = await prisma.user.findMany({\n  include: {\n    cars: true,\n  }\n});\n```\n\n```js\nimport { Prisma, PrismaClient } from \"@prisma/client\";\n\nconst prisma = new PrismaClient();\n\nconst userInclude = Prisma.validator<Prisma.UserInclude>()({\n  cars: true,\n});\n\ntype UserWithCars = Prisma.UserGetPayload<{\n  include: typeof userInclude;\n}>;\n\nconst usersWithCars = await prisma.user.findMany({\n  include: userInclude,\n});\n```\n\n```text\nGetPayload\n```\n\n```js\nmyQuery = await prisma.users.findMany({\n            [... ]\n            include: {\n                cars: {\n                  [...]\n                }}});\ntype prismaUsers = typeof myQuery\n```\n\n```js\nfunction queryUserWithCar(...) {\n  return prisma.users.findMany({\n            [... ]\n            include: {\n                cars: {\n                  [...]\n                }}});\n}\n```\n\n```js\ntype prismaUser = ReturnType<typeof queryUserWithCar> extends Promise<infer T> ? T : never\n```\n\n```text\ntypeof\n```\n\n```js\nimport { Prisma } from '@prisma/client'\n\n// 1. Define a User type that includes the \"cars\" relation. \nconst userWithCars = Prisma.validator<Prisma.UserArgs>()({\n    include: { cars: true },\n})\n\n// 2: This type will include many users and all their cars\ntype UserWithCars = Prisma.UserGetPayload<typeof userWithCars>[]\n```\n\n```js\nimport { Prisma } from '@prisma/client'\n\nasync function getUsersWithCars() {\n  const users = await prisma.user.findMany({ include: { cars: true } });\n  return users;\n}\n\ntype UsersWithCars = Prisma.PromiseReturnType<typeof getUsersWithCars>\n```\n\n```text\nfindMany\n```\n\n```text\nPromiseReturnType\n```\n\n```text\nimport { Prisma } from '@prisma/client'\n\ntype UserWithMessages = Prisma.UserGetPayload<{\n  include: {\n    Message: {\n      include: {\n        MessageParam: true;\n      };\n    };\n  };\n}>;\n```\n\n```js\ntype UserFullType = Prisma.UserGetPayload<{ select: { [K in keyof Required<Prisma.UserSelect>]: true } }>\n```\n\n```js\ninterface SelectMap {\n  User: Prisma.UserSelect\n  Post: Prisma.PostSelect\n}\n\ninterface PayloadMap<S extends (string | number | symbol)> {\n  User: Prisma.UserGetPayload<{ [K in S]: true }>\n  Post: Prisma.PostGetPayload<{ [K in S]: true }>\n}\n\ntype FullModel<M extends keyof SelectMap, S = Required<SelectMap[M]>> = PayloadMap<keyof S>[M]\n```\n\n```js\nconst user: FullModel<'User'>\n```\n\n```js\ntype ValueOf<T> = T[keyof T]\ntype PickByValue<T, V extends T[keyof T]> = { [ K in Exclude<keyof T, ValueOf<{ [ P in keyof T ]: T[P] extends V ? never : P }>> ]: T[K] }\ntype KeyOfValue<T, V extends T[keyof T]> = keyof PickByValue<T, V>\ntype PickValueByKey<T, K> = K extends keyof T ? T[K] : never\n\ninterface ModelMap {\n  Article: Article\n  User: User\n}\ninterface SelectMap {\n  Article: Prisma.ArticleSelect\n  User: Prisma.UserSelect\n}\ninterface PayloadMap<S extends (string | number | symbol)> {\n  Article: Prisma.ArticleGetPayload<{ select: { [K in S]: true } }>\n  User: Prisma.UserGetPayload<{ select: { [K in S]: true } }>\n}\ntype FullModelType<M extends ValueOf<ModelMap>, N = KeyOfValue<ModelMap, M>, S = Required<PickValueByKey<SelectMap, N>>> = PickValueByKey<PayloadMap<keyof S>, N>\nconst article: FullModelType<Article> = {}\n```\n\n```text\ntype prismaUser = users & {\n        car?: prismaCar[];\n        house?: prismaHouse;\n    }\n\ntype prismaCar = car & {\n        user?: prismaUser;\n    }\n\ntype prismaHouse = house\n```\n\n```text\nawait this.prisma.user.findMany({\n    where: {\n      patientData: {},\n    },\n    select: {\n      id: true,\n      firstName: true,\n      lastName: true,\n      email: true,\n      patientData: {\n        select: {\n          credits: true,\n        },\n      },\n      OrderHistory: {\n        select: {\n          name: true,\n          date: true,\n        },\n      },\n    },\n  });\n```\n\n```text\nexport type RecursivePartial<T> = {\n  [P in keyof T]?: RecursivePartial<T[P]>;\n};\ntype UserWithPatientAndOrderHistory = RecursivePartial<\n  Prisma.UserGetPayload<{\n    include: {\n      patientData: true;\n      OrderHistory: true;\n    };\n  }>\n>;\n```\n\n```js\nimport { type Todo, Prisma } from \"@prisma/client\";\n\nconst todoInclude = Prisma.validator<Prisma.TodoInclude>()({\n  author: {\n    select: {\n      name: true,\n      id: true,\n    },\n  },\n});\n\ntype TodoWithUser = Prisma.TodoGetPayload<{\n  include: typeof todoInclude;\n}>;\n```\n\n```js\nimport {PrismaClient} from '@prisma/client';\nimport {EmptyObject} from 'type-fest';\n\n/** All prisma model names. */\nexport type ModelName = keyof {\n    [Model in keyof PrismaClient as PrismaClient[Model] extends {findFirstOrThrow: Function}\n        ? Model\n        : never]: boolean;\n};\n\n/** For a given model, extract all the available \"include\" properties and set them all to `true`. */\nexport type IncludeAll<Model extends ModelName> =\n    NonNullable<NonNullable<Parameters<PrismaClient[Model]['findFirstOrThrow']>[0]>> extends {\n        include?: infer IncludeArg;\n    }\n        ? Record<Exclude<keyof NonNullable<IncludeArg>, '_count'>, true>\n        : EmptyObject;\n\nexport type BaseModel<Model extends ModelName> = NonNullable<\n    Awaited<ReturnType<PrismaClient[Model]['findFirstOrThrow']>>\n>;\n\nexport type JoinedModel<Model extends ModelName> = {\n    [FieldName in Extract<keyof IncludeAll<Model>, string>]: Omit<\n        ReturnType<PrismaClient[Model]['findFirstOrThrow']>,\n        'then' | 'catch' | 'finally'\n    > extends Record<FieldName, () => Promise<infer Result>>\n        ? Result\n        : `Error: failed to find relation for ${FieldName}`;\n};\n\nexport type FullModel<Model extends ModelName> = JoinedModel<Model> & BaseModel<Model>;\n```\n\n```text\nFullModel<'users'>\n```\n\n```text\n/* eslint-disable @typescript-eslint/no-require-imports */\n/* eslint-disable @typescript-eslint/no-unused-vars */\nconst fs = require(\"fs\");\n\nconst typeMap = {\n  String: \"string\",\n  Int: \"number\",\n  Float: \"number\",\n  Boolean: \"boolean\",\n  DateTime: \"Date\",\n  Decimal: \"number\",\n  BigInt: \"bigint\",\n  Json: \"any\",\n  RoleEnum: \"$.RoleEnum\",\n  OrderStatus: \"$.OrderStatus\",\n  PaymentPlatform: \"$.PaymentPlatform\",\n  Currency: \"$.Currency\",\n  TimeZone: \"$.TimeZone\",\n  StepStatus: \"$.StepStatus\",\n  AuthorType: \"$.AuthorType\",\n  Nationality: \"$.Nationality\",\n  WorkType: \"$.WorkType\",\n  Language: \"$.Language\",\n};\n\nconst jsonMap = {\n  \"Author.name\": \"StringInMultiLanguage\",\n  \"Author.biography\": \"StringInMultiLanguage\",\n  \"AuthorOnTeam.role\": \"StringInMultiLanguage[]\",\n  \"Work.title\": \"StringInMultiLanguage\",\n  \"Work.description\": \"StringInMultiLanguage\",\n  \"Genre.name\": \"StringInMultiLanguage\",\n  \"Episode.title\": \"StringInMultiLanguage\",\n  \"Episode.description\": \"StringInMultiLanguage\",\n  \"Video.metadata\": \"Metadata\",\n  \"Episode.metadata\": \"Metadata\",\n};\n\nfunction processType(type, isArray) {\n  let processedType = typeMap[type] || type;\n  if (isArray) processedType += \"[]\";\n  return processedType;\n}\n\nfunction processProperty(prop, modelName) {\n  if (!prop.trim()) return \"\";\n\n  const [name, type] = prop.trim().split(/\\s+/);\n  if (!type) return \"\";\n\n  const isArray = type.includes(\"[]\");\n  const isOptional = type.endsWith(\"?\");\n  const baseType = type.replace(\"[]\", \"\").replace(\"?\", \"\");\n  const isFileId = name.includes(\"FileId\");\n\n  const finalType =\n    jsonMap[`${modelName}.${name}`] || processType(baseType, isArray);\n  let result = `  ${name}${isOptional ? \"?: \" : \": \"}${finalType};`;\n  if (isFileId) {\n    result = result.concat(\n      `${name.replace(\"FileId\", \"File\")} ${isOptional ? \"?: \" : \": \"} ${isArray ? \"File[]\" : \"File\"};`,\n    );\n  }\n  return result;\n}\n\nfunction processModel(match, modelName, properties) {\n  const propertyList = properties\n    .split(\" \")\n    .slice(1, -1)\n    .join(\" \")\n    .split(/\\s+/)\n    .filter(Boolean);\n\n  const processedProperties = [];\n  for (let i = 0; i < propertyList.length; i += 2) {\n    if (i + 1 < propertyList.length) {\n      const prop = `${propertyList[i]} ${propertyList[i + 1]}`;\n      const processed = processProperty(prop, modelName);\n      if (processed) processedProperties.push(processed);\n    }\n  }\n\n  return `export type ${modelName} = {\\n${processedProperties.join(\"\\n\")}\\n};`;\n}\n\ntry {\n  const schemaContent = fs.readFileSync(\"./prisma/schema.prisma\", \"utf-8\");\n  const modelsSection = schemaContent.split(\"//models\")[1];\n\n  if (!modelsSection) {\n    throw new Error(\"Could not find models section in schema.prisma\");\n  }\n\n  const lines = modelsSection.split(\"\\n\");\n  const filteredLines = lines.filter(\n    (line) =>\n      !line\n        .replace(/\\s+/g, \" \")\n        .replace(/@\\w+(\\([^)]*\\))?/g, \"\")\n        .replace(/\\s+/g, \" \")\n        .trim()\n        .replaceAll(\")\", \"\")\n        .replace(/\\s+/g, \" \")\n        .startsWith(\"//\"),\n  );\n  for (let i = 0; i < filteredLines.length; i++) {\n    if (filteredLines[i].includes(\"//\")) {\n      const splash = filteredLines[i].indexOf(\"//\");\n      filteredLines[i] = filteredLines[i].slice(0, splash);\n    }\n  }\n  const modelsSectionClean = filteredLines.join(\"\\n\");\n\n  const processedModels = modelsSectionClean\n    .replace(/\\s+/g, \" \")\n    .replace(/@\\w+(\\([^)]*\\))?/g, \"\")\n    .replace(/\\s+/g, \" \")\n    .trim()\n    .replaceAll(\")\", \"\")\n    .replace(/\\s+/g, \" \")\n    .replace(/(\\w+)\\s*{([^}]+)}/g, processModel)\n    .replaceAll(\"model\", \"\");\n\n  const typesPath = \"./src/config/types/prisma.type.ts\";\n  let indexContent = fs.readFileSync(typesPath, \"utf-8\");\n  const modelsLine = indexContent.indexOf(\"//models\");\n\n  indexContent = `${indexContent.slice(0, modelsLine)}\\n\\n//models\\n${processedModels}`;\n  fs.writeFileSync(typesPath, indexContent);\n\n  console.log(\"Successfully updated TypeScript types\");\n} catch (error) {\n  console.error(\"Error processing schema:\", error);\n  process.exit(1);\n}\n```\n\n```text\nimport * as $ from \"@prisma/client\";\n```\n\n```text\n\"gen_type\":\"node ./src/config/prisma/gen_type.js && yarn lint\"\n```\n\n========================================\n\nComments:\n- Upvoting because your solution does not need to create a function just to retrieve a type :) Thanks!\n- How would you do this if you have extended your prisma client?","metadata":{"transformedAt":"2026-08-18T18:33:14.811Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":526,"estimatedTokens":3096}}4{"id":"stack-71442989","source":"stackoverflow","questionId":71442989,"title":"How to add type definitions for includes in a Prisma model?","tags":["typescript","prisma"],"text":"Title: How to add type definitions for includes in a Prisma model?\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nThe example in the documentation looks like this:\n\n```\nconst getUser = await prisma.user.findUnique({\n where: {\n id: 1,\n },\n include: {\n posts: {\n select: {\n title: true,\n },\n },\n },\n})\n```\n\nBut when I want to read the property `getUser.posts` I get the following error:\n\n```\nTS2339: Property 'posts' does not exist on type 'User'.\n```\n\nWhere can I find the correct type definitions the for the includes option?\n\n========================================\n\nCode:\n```text\nconst getUser = await prisma.user.findUnique({\n  where: {\n    id: 1,\n  },\n  include: {\n    posts: {\n      select: {\n        title: true,\n      },\n    },\n  },\n})\n```\n\n```text\nTS2339: Property 'posts' does not exist on type 'User'.\n```\n\n```text\ngetUser.posts\n```\n\n```js\nimport { Prisma } from '@prisma/client'\n\ntype UserWithPosts = Prisma.UserGetPayload<{\n  include: { posts: true }\n}>\n```\n\n========================================\n\nComments:\n- What's your schema look like?\n- The docs for this are at prisma.io/docs/concepts/components/prisma-client/&hellip;\n- We use several nested includes in our query so I'm fear it turns into a nightmare to write proper typed code. We then need to use `Prisma.PostGetPayload` as a type for intermediary variables, so we declare several time the same relationship of payloads...\n- Thank you for this. Couldn't find anything at all about this in the documentation.\n- Thanks! It's a pain, but it's nice that it can be achieved! I finished up with huge Signatures: `Promise>>` and much larger too... but doable","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":72,"estimatedTokens":410}}5{"id":"stack-70449092","source":"stackoverflow","questionId":70449092,"title":"Reason: `object` (\"[object Date]\") cannot be serialized as JSON. Please only return JSON serializable data types","tags":["javascript","next.js","prisma","serializable"],"text":"Title: Reason: `object` (\"[object Date]\") cannot be serialized as JSON. Please only return JSON serializable data types\nTags: javascript, next.js, prisma, serializable\nSource: Stack Overflow\n\nQuestion:\nI am using Prisma and Next.js. When I try to retrieve the content from Prisma in `getStaticProps` it does fetch the data but I can't pass it on to the main component.\n\n```\nexport const getStaticProps = async () => {\n const prisma = new PrismaClient();\n const newsLetters = await prisma.newsLetters.findMany();\n console.log(newsLetters);\n\n return {\n props: {\n newsLetters: newsLetters,\n },\n };\n};\n```\n\nAs you can see in this image it is fetching as well as printing the content.\n\nhttps://i.sstatic.net/d34op.png\n\nBut when I pass I get the following error for passing it as props\n\n```\nReason: `object` (\"[object Date]\") cannot be serialized as JSON. Please only return JSON serializable data types.\n```\n\n========================================\n\nTop Answer:\nIf you're using **TypeScript**, you can't change the type of `createdAt` to a string or number. This won't work:\n\n```\nnewsLetter.createdAt = newsLetter.createdAt.toString();\n// Error: Type 'string' is not assignable to type 'Date'.\n```\n\nInstead, you can use `JSON.stringify` inside `JSON.parse` to create a serializable object:\n\n```\nexport const getStaticProps = async () => {\n const prisma = new PrismaClient();\n const newsLetters = await prisma.newsLetters.findMany();\n\n return {\n props: {\n newsLetters: JSON.parse(JSON.stringify(newsLetters)) // <===\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport const getStaticProps = async () => {\n  const prisma = new PrismaClient();\n  const newsLetters = await prisma.newsLetters.findMany();\n  console.log(newsLetters);\n\n  return {\n    props: {\n      newsLetters: newsLetters,\n    },\n  };\n};\n```\n\n```text\nReason: `object` (\"[object Date]\") cannot be serialized as JSON. Please only return JSON serializable data types.\n```\n\n```text\ngetStaticProps\n```\n\n```js\n// your data\nlet newsLetters = [\n    {\n        id: 'your-id',\n        email: 'email@example.com',\n        createdAt: new Date()\n    }\n];\n\n// map the array\nnewsLetters.map(x => {\n    x.createdAt = Math.floor(x.createdAt / 1000);\n    return x;\n})\n\n// use newsLetters now\nconsole.log(newsLetters);\n```\n\n```text\nfor (const element of newsLetters) {\n  element.createdAt = element.createdAt.toString()\n}\n```\n\n```text\nnewsLetter.createdAt = newsLetter.createdAt.toString();\n// Error: Type 'string' is not assignable to type 'Date'.\n```\n\n```text\nexport const getStaticProps = async () => {\n  const prisma = new PrismaClient();\n  const newsLetters = await prisma.newsLetters.findMany();\n\n  return {\n     props: {\n        newsLetters: JSON.parse(JSON.stringify(newsLetters)) // <===\n     }\n  }\n}\n```\n\n```text\ncreatedAt\n```\n\n```text\nJSON.stringify\n```\n\n```text\nJSON.parse\n```\n\n```bash\nyarn add next-superjson-plugin\n```\n\n```js\n// next.config.js\nmodule.exports = {\n  experimental: {\n    swcPlugins: [\n      [\n        'next-superjson-plugin',\n        {\n          excluded: [],\n        },\n      ],\n    ],\n  },\n}\n```\n\n```text\nsuperjson\n```\n\n```text\ngetServerSideProps\n```\n\n```text\ngetInitialProps\n```\n\n```text\ngetStaticProps\n```\n\n```text\nnext.config.js\n```\n\n```text\ncreatedAt DateTime @default(now())\n```\n\n```text\nimport { formatDistance } from 'date-fns'\n\nconst newsLetters = await prisma.newsLetters.findMany();\nconst serializedNesLetters= newsLetters.map((newsLetter)=>({\n     ...newsLetter, \n     createdAt:formatDistance(new Date(newsLetter.timestamp),new Date())\n}))\n```\n\n```text\nexport async function getStaticProps() {\n  const storeInfo = await getStoreInfo()\n\n  return {\n    props: {\n      storeInfo: {\n        ...storeInfo,\n        createdAt: storeInfo?.createdAt.toISOString(),\n        updatedAt: storeInfo?.updatedAt.toISOString(),\n      },\n    },\n  }\n}\n```\n\n```text\ncreated: created.toString() - throws the error\n  created: new Date(created).toLocaleDateString() - working\n```\n\n========================================\n\nComments:\n- If you don't need to edit the date later (probably not with a created at), you can convert it to a legible string instead of a unix timestamp. newsLetters.map(x => { x.createdAt = x.createdAt.toString() return x; })\n- the conversion snippet you proposed doesn't work since element.createdAt remains of type DateTime, and you can't assign a string to it\n- @L0g1x , its working for me, I needed it so frequently, I put it in a helper function and used it repeatedly. In what context did it not work for you? Perhaps the DateTime object you were working with was different?\n- @GreggoryWiley I think L0g1x is using typescript\n- Not pretty, yet pragmatic. Thank you for this workaround.\n- thanks! had to restart server a couple times before it starts working though","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":221,"estimatedTokens":1195}}6{"id":"stack-55404678","source":"stackoverflow","questionId":55404678,"title":"How to upsert new record in Prisma without an ID?","tags":["node.js","prisma","prisma-graphql"],"text":"Title: How to upsert new record in Prisma without an ID?\nTags: node.js, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using Prisma (https://www.prisma.io) as ORM. I want to check for duplicates when store data and, if not exists, create a new record. \n\nI thought I could do that with upsert method provided by Prisma and available in the generated client, but the where clause of that method only works with id (or @unique fields), but if the record doesn't exist, there isn't any id to provide.\n\nI provide an example of the problem.\n\n**datamodel.prisma**\n\n```\ntype System {\n id: ID! @unique\n performances: [SystemPerformance!]! @relation(name: \"PerformanceBySystem\" onDelete: CASCADE)\n name: String! @unique\n}\n\ntype SystemPerformance {\n id: ID! @unique\n system: System! @relation(name: \"PerformanceBySystem\")\n date: DateTime!\n perf1: Float\n perf2: Float\n}\n```\n\n**seed.js**\n\n```\nconst { prisma } = require('./generated/prisma-client');\nasync function main(){\n await prisma.createSystem({\n name: 's1',\n });\n await prisma.createSystem({\n name: 's2',\n });\n await prisma.createSystem({\n name: 's3',\n });\n}\nmain();\n```\n\nAfter creation there is a database with three Systems without performances. I'm trying to insert a new SystemPerformance if there aren't any that have same date and same System. I have tried\n\n```\nconst { prisma } = require('./prisma/generated/prisma-client');\n\nconst perf = await prisma.upsertSystemPerformance({\n where: {\n system: {name: 's1'},\n date: \"2019-03-12T00:01:06.000Z\"\n },\n update: {\n perf1: 13.45,\n perf2: 18.93\n },\n create: {\n system: {\n connect: { name: 's1' }\n },\n date: \"2019-03-12T00:01:06.000Z\",\n perf1: 13.45,\n perf2: 18.93\n }\n})\n```\n\nBut an exception is thrown:\n\n*UnhandledPromiseRejectionWarning: Error: Variable '$where' expected value of type 'SystemPerformanceWhereUniqueInput!' but got: {\"system\":{\"name\":'s1'},\"date\":\"2019-03-12T00:01:06.000Z\"}. Reason: 'system' Field 'system' is not defined in the input type 'SystemPerformanceWhereUniqueInput'*\n\nThe only solution I have found is check for existence and then update or create, but I wanted to do it with upsert.\n\n```\nlet check = await prisma.$exists.SystemPerformance({\n system: {name: 's1'},\n date: \"2019-03-12T00:01:06.000Z\"\n });\nlet perfo;\nif (check){\n const sysPerf = await prisma.systemPerformances({where:{system: {name: 's1'}, date: \"2019-03-12T00:01:06.000Z\"}})\n .$fragment(`\n {\n id\n }\n `);\n perfo = await prisma.updateSystemPerformance({\n where: {id: sysPerf[0].id},\n data: {\n perf1: 13.45,\n perf2: 18.93\n }\n })\n}\nelse {\n perfo = await prisma.createSystemPerformance({\n system: {\n connect: { name: 's1' }\n },\n date: \"2019-03-12T00:01:06.000Z\",\n perf1: 13.45,\n perf2: 18.93\n }\n})\n```\n\nIs there a way to do that with upsert?\n\n========================================\n\nTop Answer:\nIf you are still down here without an answer, I used a combination from @Antoine's answer and another SO answer:\n\n```\nmodel Likes {\n id String @id @unique @default(uuid())\n user_id String\n tag String\n auth_user AuthUser @relation(references: [id], fields: [user_id], onDelete: Cascade)\n\n @@unique([user_id, tag], name: \"user_id_tag\") // Then I was able to upsert via the following:\n\n```\nprisma.likes.upsert({\n where: {\n user_id_tag: { // <-- And this bit is important\n user_id: user.userId,\n tag: tag.tag\n }\n },\n update: {},\n create: tag\n})\n```\n\n========================================\n\nCode:\n```text\ntype System {\n  id: ID! @unique\n  performances: [SystemPerformance!]! @relation(name: \"PerformanceBySystem\" onDelete: CASCADE)\n  name: String! @unique\n}\n\ntype SystemPerformance {\n  id: ID! @unique\n  system: System! @relation(name: \"PerformanceBySystem\")\n  date: DateTime!\n  perf1: Float\n  perf2: Float\n}\n```\n\n```text\nconst { prisma } = require('./generated/prisma-client');\nasync function main(){\n  await prisma.createSystem({\n    name: 's1',\n  });\n  await prisma.createSystem({\n    name: 's2',\n  });\n  await prisma.createSystem({\n    name: 's3',\n  });\n}\nmain();\n```\n\n```text\nconst { prisma } = require('./prisma/generated/prisma-client');\n\nconst perf = await prisma.upsertSystemPerformance({\n       where: {\n         system: {name: 's1'},\n         date: \"2019-03-12T00:01:06.000Z\"\n       },\n       update: {\n         perf1: 13.45,\n         perf2: 18.93\n       },\n       create: {\n        system: {\n            connect: { name: 's1' }\n        },\n        date: \"2019-03-12T00:01:06.000Z\",\n        perf1: 13.45,\n        perf2: 18.93\n       }\n})\n```\n\n```text\nlet check = await prisma.$exists.SystemPerformance({\n            system: {name: 's1'},\n            date: \"2019-03-12T00:01:06.000Z\"\n        });\nlet perfo;\nif (check){\n  const sysPerf = await prisma.systemPerformances({where:{system: {name: 's1'}, date: \"2019-03-12T00:01:06.000Z\"}})\n            .$fragment(`\n            {\n                id\n            }\n            `);\n  perfo = await prisma.updateSystemPerformance({\n    where: {id: sysPerf[0].id},\n            data: {\n              perf1: 13.45,\n              perf2: 18.93\n            }\n   })\n}\nelse {\n  perfo = await prisma.createSystemPerformance({\n    system: {\n      connect: { name: 's1' }\n    },\n    date: \"2019-03-12T00:01:06.000Z\",\n    perf1: 13.45,\n    perf2: 18.93\n  }\n})\n```\n\n```text\nwhere\n```\n\n```text\ndate\n```\n\n```text\ndate: DateTime! @unique\n```\n\n```text\nwhere: {\n    id: sysPerf[0].id ? sysPerf[0].id : 0\n},\n```\n\n```text\nimport ObjectId from \"bson-objectid\";\n\nproviders: {\n        upsert: data.item?.map((item: Prisma.ItemCreateInput) => ({\n          where: {\n            id: item.id || ObjectId().toString(),\n          },\n          update: {\n            // ...data\n          },\n          create: {\n            // ...data\n          },\n        })),\n      },\n}\n```\n\n```text\nMongo\n```\n\n```text\nmodel Likes {\n  id         String     @id @unique @default(uuid())\n  user_id    String\n  tag        String\n  auth_user  AuthUser   @relation(references: [id], fields: [user_id], onDelete: Cascade)\n\n  @@unique([user_id, tag], name: \"user_id_tag\")  // <-- this is the unique constraint\n  @@index([user_id])\n  @@map(\"likes\")\n}\n```\n\n```text\nprisma.likes.upsert({\n    where: {\n        user_id_tag: { // <-- And this bit is important\n            user_id: user.userId,\n            tag: tag.tag\n        }\n    },\n    update: {},\n    create: tag\n})\n```\n\n```js\nconst seedAddress = async () => {\n  const addresses = [\n    {\n      street: \"Merry Poppins\",\n      number: \"1231\",\n      apartment: \"301\",\n      community: \"London\",\n      referenceText: \"Near to the North\",\n      zone: \"England\",\n    },\n    {\n      street: \"Principal Street\",\n      number: \"123\",\n      apartment: \"4B\",\n      community: \"El Bosque\",\n      referenceText: \"Near Supermarket\",\n      zone: \"Main\",\n    },\n    {\n      street: \"Avenida del Mar\",\n      number: \"456\",\n      apartment: null,\n      community: null,\n      referenceText: \"Frente a la playa\",\n      zone: \"Viña del Mar\",\n    },\n  ];\n\n  // Como en esta tabla no hay un campo unico adicional al id\n  // se utiliza se busca y actualiza.\n\n  const addressesResult = await Promise.all(addresses.map(async (address) => {\n    const transactionResult = await prisma.$transaction( async (tx) => {\n      //search for address.street and update or create\n      const result = await tx.address.findFirst({ where: { street: address.street }})\n\n      console.log('result', result)\n\n      if (result) {\n        return await tx.address.update({\n          where: { id: result.id },\n          data: address,\n        })\n      } else {\n        return await tx.address.create({\n          data: address,\n        })\n      }\n    })\n    return transactionResult\n\n  }))\n\n  console.log('\\n\\nADDRESS RESULTS: \\n', addressesResult);\n}\n```\n\n========================================\n\nComments:\n- Upsert accepts only unique fields as input in `where` clause. I fear you will have to go with workaround where you query record and then use upsert or update / create depending upon whether record exists.\n- I was afraid of that. I asked if there was a better solution. Thank you for your answer.\n- One dirty hack that I am using, and it works for me is using a sentinal value for id that doesn't exist: ` where: { id: id ?? \"does not exist\" }`\n- A recommendation: use an IDE which understands prisma. I've got VScode and TypeScript, and I get `where:` highlighted as an error, with an explanation that my where clause is not assignable to \"UserWhereUniqueInput\" - saving a lot of time with trying to run the code or trying to find explanations.\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.\n- It works on mariadb\n- in this getting error while data not exist return `ConnectorError(ConnectorError { user_facing_error: None, kind: RecordDoesNotExist, transient: false })` insted of create record any idea ?\n- Small addition: there is already a name to the generated unique key constraint, so you can avoid defining in model file and just use generated name.","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":367,"estimatedTokens":2230}}7{"id":"stack-69274503","source":"stackoverflow","questionId":69274503,"title":"\"Property does not exist\" when I want to use model added in Prisma.schema","tags":["next.js","prisma","prisma-graphql","prisma2"],"text":"Title: \"Property does not exist\" when I want to use model added in Prisma.schema\nTags: next.js, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm working on ReactJS project with NextJS Framework and Prisma to manage connection and queries to the DB.\n\nOn my local project the **Support** model is found and when I use it in my API and build my project it's ok.\n\nBut when I push my project on production server (Plesk), the build shows me this typescript error because it doesn't find the **Support** model:\n\n```\n./src/pages/api/support/index.ts:27:26\nType error: Property 'support' does not exist on type 'PrismaClient'.\n```\n\nThe path `./src/pages/api/support/index.ts` is where I want to use the **Support** model\n\nMy `prisma.schema`:\n\n```\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_CONNECTION\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel User {\n id Int @id @unique @default(autoincrement())\n gender String?\n firstName String\n lastName String\n email String @unique\n phone String\n birthday DateTime?\n income Float?\n pincode Int?\n points Float?\n token String @db.Text\n ipAddress String\n kyc Kyc[]\n createdAt DateTime @default(now())\n updatedAt DateTime?\n isValidated Boolean @default(false)\n roleId Int\n role Role @relation(fields: [roleId], references: [id])\n Alerts Alerts[]\n Support Support[]\n}\n\nmodel Kyc {\n id Int @id @unique @default(autoincrement())\n name String\n validated Boolean @default(false)\n path String\n createdAt DateTime @default(now())\n updatedAt DateTime? @updatedAt\n user User @relation(fields: [userId], references: [id])\n userId Int\n}\n\nmodel Alerts {\n id Int @id @unique @default(autoincrement())\n type TYPE @default(NOBLOCKED)\n message String @db.Text\n transferId Int @unique\n fromUserId Int\n read Boolean @default(false)\n createdAt DateTime @default(now())\n user User @relation(fields: [fromUserId], references: [id])\n}\n\nmodel Role {\n id Int @id @unique @default(autoincrement())\n name String\n User User[]\n}\n\nmodel Support {\n id Int @id @unique @default(autoincrement())\n subject String\n message String @db.Text\n createdAt DateTime @default(now())\n userId Int\n user User @relation(fields: [userId], references: [id])\n}\n\nenum TYPE {\n BLOCKED\n NOBLOCKED\n}\n```\n\nI don't know if I need to use `prisma migrate dev` or `prisma migrate deploy` each time I push the latest changes.\n\n========================================\n\nTop Answer:\nI forgot to await\n\n```\nconst user = prisma.user.findUnique({ \n where: {\n userId: authorUserId\n },\n select: {\n id: true\n }\n})\n```\n\n**but should be:**\n\n```\nconst user = **await** prisma.user.findUnique({ \n where: {\n userId: authorUserId\n },\n select: {\n id: true\n }\n})\n```\n\n========================================\n\nCode:\n```text\n./src/pages/api/support/index.ts:27:26\nType error: Property 'support' does not exist on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.\n```\n\n```text\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_CONNECTION\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel User {\n  id              Int       @id @unique @default(autoincrement())\n  gender          String?\n  firstName       String\n  lastName        String\n  email           String    @unique\n  phone           String\n  birthday        DateTime?\n  income          Float?\n  pincode         Int?\n  points          Float?\n  token           String    @db.Text\n  ipAddress       String\n  kyc             Kyc[]\n  createdAt       DateTime  @default(now())\n  updatedAt       DateTime?\n  isValidated     Boolean   @default(false)\n  roleId          Int\n  role            Role      @relation(fields: [roleId], references: [id])\n  Alerts          Alerts[]\n  Support Support[]\n}\n\nmodel Kyc {\n  id        Int       @id @unique @default(autoincrement())\n  name      String\n  validated Boolean   @default(false)\n  path      String\n  createdAt DateTime  @default(now())\n  updatedAt DateTime? @updatedAt\n  user      User      @relation(fields: [userId], references: [id])\n  userId    Int\n}\n\nmodel Alerts {\n  id         Int      @id @unique @default(autoincrement())\n  type       TYPE     @default(NOBLOCKED)\n  message    String   @db.Text\n  transferId Int      @unique\n  fromUserId Int\n  read       Boolean  @default(false)\n  createdAt  DateTime @default(now())\n  user       User     @relation(fields: [fromUserId], references: [id])\n}\n\nmodel Role {\n  id   Int    @id @unique @default(autoincrement())\n  name String\n  User User[]\n}\n\nmodel Support {\n  id        Int     @id @unique @default(autoincrement())\n  subject   String\n  message   String  @db.Text\n  createdAt DateTime  @default(now())\n  userId          Int\n  user            User      @relation(fields: [userId], references: [id])\n}\n\nenum TYPE {\n  BLOCKED\n  NOBLOCKED\n}\n```\n\n```text\n./src/pages/api/support/index.ts\n```\n\n```text\nprisma.schema\n```\n\n```text\nprisma migrate dev\n```\n\n```text\nprisma migrate deploy\n```\n\n```text\nPost\n```\n\n```text\nawait prisma.posts\n```\n\n```text\nawait prisma.posts\n```\n\n```text\nconst user = prisma.user.findUnique({ \n  where: {\n    userId: authorUserId\n  },\n  select: {\n    id: true\n  }\n})\n```\n\n```text\nconst user = **await** prisma.user.findUnique({ \n  where: {\n    userId: authorUserId\n  },\n  select: {\n    id: true\n  }\n})\n```\n\n```text\nprisma generate\n```\n\n```text\nCTRL + SHIFT + P\n```\n\n```text\nrestart TS Server\n```\n\n```text\n./node_modules/.prisma/client/index.d.ts\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nctrl + P\n```\n\n```text\n> reload window\n```\n\n```text\nUser\n```\n\n```text\n@@map(\"user\")\n```\n\n```text\nawait prisma.user.delete({ ...\n```\n\n```text\nuser\n```\n\n```text\n@@map\n```\n\n```text\nOTP\n```\n\n```text\n@@map(\"otp)\n```\n\n```text\nprisma.oTP.delete({ ...\n```\n\n```text\nexport class PrismaModule extends PrismaClient {}\n```\n\n```text\n@Injectable()\nexport class PrismaService extends PrismaClient {}\n```\n\n```text\nPrismaClient\n```\n\n```text\nprisma.module.ts\n```\n\n```text\nprisma.service.ts\n```\n\n```js\nimport type { BoardMobile} from '@prisma/client'; // ❌ it doesn't consider joined objects\nconst { data: boardMobiles, error: fetchError } = await useFetch(`/api/boards/${route.params.id}/mobiles`)\n\n// ref\nconst inTransitMobiles = ref<typeof boardMobiles.value>([]) // ✅ it's ok\nconst availableMobiles = ref<BoardMobile[]>([]) // ❌ it has problem with \"join\" mobile property\n```\n\n```js\n<MobileSquareItem\n v-for=\"bm in inTransitMobiles\" \n :id=\"bm.mobile.number\" // ✅ it's ok\n :key=\"bm.mobileId\" \n color=\"yellow\"\n/>\n\n<MobileSquareItem\n v-for=\"bm in availableMobiles\" \n :id=\"bm.mobile.number\" // ❌ it has problem with \"join\" mobile property\n :key=\"bm.mobileId\" \n color=\"green\"\n/>\n```\n\n```text\ntypeof\n```\n\n```text\ninTransitMobiles\n```\n\n```text\navailableMobiles\n```\n\n```text\n.next\n```\n\n```text\n.turbo\n```\n\n```text\ngenerated/prisma\n```\n\n```text\nnpm install\n```\n\n```text\nyarn install\n```\n\n```text\npnpm install\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nyarn prisma generate\n```\n\n```text\ndatabase/src/index.ts\n```\n\n```text\nconsole.log(Object.keys(prisma))\n```\n\n```js\n// something like this:\ngenerator client {\n    provider = \"prisma-client-js\"\n    output   = \"../app/generated/prisma\"\n}\n```\n\n```text\nimport { PrismaClient } from \"../generated/prisma\";\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\"; // this assumes default path: app/generated/prisma/client\n```\n\n========================================\n\nComments:\n- Did you ran `prisma generate` to generate Prisma client after making changes on Prisma schema ? `prisma migrate dev` will also generate Prisma client along with migration.\n- In addition to what @PasinduDilshan mentioned (which is a likely cause of the problem), is this issue only with the Support model? Do all other models work as expected?\n- @TasinIshmam yes every other models worked properly. This error has been only for Support model because I had already pushed news models to the production server and I never had this type of error. This could be because I just started to use `prisma migrate deploy` with this Support model. And this is exactly what @Pasindudilshan said with the `prisma migrate dev` which also generates Prisma client and why I never had this error before.\n- Yes, `prisma migrate deploy` does not generate the client, so you have to run `prisma generate` as was mentioned. Just to clarify, you have been able to solve the problem now?\n- Yes everything works fine ! Thanks you guys for your help !\n- Also If you use VS Code sometimes you need to restart TS server,,\n- If anyone has this issue in WebStrom/IntelliJ: add a new JS library pointing to `node_modules&#47;@prisma&#47;client` in IDE settings (Languages & Frameworks -> JavaScript -> Libraries -> Add...)\n- If you are using Typescript, open up the Command Palette (Ctrl Shift P), and typing \"Restart Typescript Server\", and press enter. Would help as well, without the need to restart VSCode\n- I remember that I had the same problem and fixed it with that, but now it doesn't work anymore on any device after restarts and it won't build, so not a vscode issue this time. What now??\n- running $ prisma generate worked for me. I read through the documentation and ideally prisma generate should be executed every time you make changes in the prisma.schema file. Here's the reference prisma.io/docs/concepts/components/&hellip;\n- Or simply open the file ./node_modules/.prisma/client/index.d.ts\n- i'ts works perfect for me\n- Thanks, this worked. Is there a way to avoid doing this? I know every platform and ecosystem has its quirks, but this is just as annoying as Python's package management systems\n- Hi Bereket G, As far as i can tell your answer is the same as the accepted one.","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":49,"totalLines":452,"estimatedTokens":2405}}8{"id":"stack-68579505","source":"stackoverflow","questionId":68579505,"title":"How to get enums in prisma client?","tags":["node.js","postgresql","prisma"],"text":"Title: How to get enums in prisma client?\nTags: node.js, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\ncan I get a list of enums values of a model on the client-side like for select option?\n\nSample enum\n\n```\nenum user_type {\n superadmin\n admin\n user\n}\n```\n\nI want this as a select-option on the client-side. How can I get them as JSON data?\n\n========================================\n\nTop Answer:\nWhen you generate Prisma Client, it generates TypeScript interfaces for your models and enum types.\n\nyou can do\n\n```\nimport { PrismaClient, user_type } from '@prisma/client'\n```\n\nand this will give you the user_type types declarations\n\n========================================\n\nCode:\n```text\nenum user_type {\n    superadmin\n    admin\n    user\n}\n```\n\n```js\nimport {user_type } from \"@prisma/client\";\n\nlet foo: user_type = \"superadmin\";\n// use like any other type/enum\n```\n\n```js\n// file: node_modules/.prisma/client/index.d.ts\nexport const user_type: {\n  superadmin: 'superadmin',\n  admin: 'admin',\n  user: 'user'\n};\n```\n\n```text\nuser_type\n```\n\n```text\nuser_type\n```\n\n```text\nimport { PrismaClient, user_type } from '@prisma/client'\n```\n\n```text\nprisma generate\n```\n\n========================================\n\nComments:\n- another approach using `graphql` here : stackoverflow.com/a/57877222/9339924","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":79,"estimatedTokens":325}}9{"id":"stack-71101647","source":"stackoverflow","questionId":71101647,"title":"how to ignore extra fields when storing prisma data?","tags":["prisma"],"text":"Title: how to ignore extra fields when storing prisma data?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI'm loading some data from a CSV file that has some extra notes fields that I don't want in the DB. Is there an option to just ignore extra fields when storing to the DB?\n\nI think mongoose did this by default - which does have a downside that stuff goes missing without warning if your schema is wrong but... thats what i want in this case.\n\nOtherwise what is a way to reflect and get the schema so I can remove extra fields from the data manually?\n\nI'm getting this error on `.create`\n\n```\nUnknown arg `notes` in data.notes for type WalletCreateInput. \nDid you mean `name`? \nAvailable args:\n...\n```\n\n========================================\n\nTop Answer:\nLate to the party, but there is a way around this.\nIf you use the \"fieldReference\" preview feature:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"fieldReference\"]\n}\n```\n\nYou can then create the following to strip out any extra keys.\n\n```\nfunction stripPrisma(input: {fields:{}},data: T) : T {\n \n let validKeys = Object.keys(input.fields);\n let dataCopy: any = {...data};\n for(let key of Object.keys(data)) {\n\n if(!(validKeys.includes(key))) {\n delete dataCopy[key];\n }\n }\n return dataCopy as T;\n}\n```\n\nAnd use it like this\n\n```\ndata = stripPrisma(prisma.myTable, data);\nprisma.myTable.create({data:data});\n```\n\nIt is not perfect, since it will only be able to use \"checked input\", meaning you can only use the foreign key in your input and not the foreign object.\n\n========================================\n\nCode:\n```text\nUnknown arg `notes` in data.notes for type WalletCreateInput. \nDid you mean `name`? \nAvailable args:\n...\n```\n\n```text\n.create\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"fieldReference\"]\n}\n```\n\n```text\nfunction stripPrisma<T extends {}>(input: {fields:{}},data: T) : T {\n    \n    let validKeys = Object.keys(input.fields);\n    let dataCopy: any = {...data};\n    for(let key of Object.keys(data)) {\n\n        if(!(validKeys.includes(key))) {\n            delete dataCopy[key];\n        }\n    }\n    return dataCopy as T;\n}\n```\n\n```text\ndata = stripPrisma(prisma.myTable, data);\nprisma.myTable.create({data:data});\n```\n\n```js\npolishUser(user); // remove extra fields but has no explicit types\npolishDefaultUser(user); // remove extra fields and is suitable for \"data\" field in queries\npolishPartialUser(user); // remove extra fields and is suitalble for \"where\" field in queries\n```\n\n========================================\n\nComments:\n- You can try destructuring the values\n- right but then i need to know the schema of the prisma object, or i have to hadrwire all my filters. How do i get the list of required fields in a prisma class/type?\n- ok thanks. so is there a runtime way to get the schema so I can remove extra fields from the data manually without hardwiring it at compile time - and so i can use the same code for multiple classes?","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":112,"estimatedTokens":750}}10{"id":"stack-68476229","source":"stackoverflow","questionId":68476229,"title":"M1 Related! - Prisma: Can't reach database server at `database`:`5432`","tags":["node.js","postgresql","docker","prisma","apple-m1"],"text":"Title: M1 Related! - Prisma: Can't reach database server at `database`:`5432`\nTags: node.js, postgresql, docker, prisma, apple-m1\nSource: Stack Overflow\n\nQuestion:\nSince I have moved to the new Apple Silicon architecture my docker setup with nextjs and postgres is not working anymore. The database inside the docker cannot be found by the nextjs server where I am using prisma.\n\nThe prisma client can't reach the postgres database on port 5432.\n\nCan't reach database server at `test-postgres`:`5432`\n\nThe migration also does not work and returns the same error above.\n\n```\ndocker-compose run --publish 5555:5555 next npx prisma migrate dev\n```\n\ndocker-compose.yml\n\n```\npostgres:\n container_name: 'test-postgres'\n restart: unless-stopped\n image: 'postgres:13'\n ports:\n - '15432:5432'\n volumes:\n - 'pgdata:/var/lib/postgresql/data/'\n environment:\n POSTGRES_PASSWORD: postgres\n```\n\n.env\n\n```\nDATABASE_URL=\"postgres://postgres:postgres@localhost:15432/postgres\"\n```\n\nI have also added the arm binary target to the schema.prisma\nschema.prisma\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n binaryTargets = [\"native\", \"debian-openssl-1.1.x\", \"linux-arm-openssl-1.1.x\", \"linux-musl\"]\n previewFeatures = [\"orderByRelation\", \"selectRelationCount\"]\n}\n```\n\nThe postgres container is actually running and I can see it through the Docker Desktop Dashboard. One thing I have noticed inside the postgres container was this ERROR:\n\n```\n2021-07-21 12:52:58.927 UTC [76] ERROR: relation \"_prisma_migrations\" does not exist at character 126\n```\n\nHave someone experienced it before and found a solution for it?\n\n[EDIT]\n\n### How to reproduce\n\nclone repo, README.md and see expected behaviour on a M1 Apple Silicon Machine: https://github.com/baristikir/prisma-postgres-M1\n\n========================================\n\nTop Answer:\nI had this issue on m1 mac mini, **the solution was changing the version of node from v16.16.0(image node:16) to v17.9.1(node:17), we tried on node:18 it works also**.\nI changed Dockerfile\nfrom\n\n```\nFROM node:16\n```\n\nto\n\n```\nFROM node:17\n```\n\n========================================\n\nCode:\n```sh\ndocker-compose run --publish 5555:5555 next npx prisma migrate dev\n```\n\n```text\npostgres:\n    container_name: 'test-postgres'\n    restart: unless-stopped\n    image: 'postgres:13'\n    ports:\n      - '15432:5432'\n    volumes:\n      - 'pgdata:/var/lib/postgresql/data/'\n    environment:\n      POSTGRES_PASSWORD: postgres\n```\n\n```text\nDATABASE_URL=\"postgres://postgres:postgres@localhost:15432/postgres\"\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  binaryTargets   = [\"native\", \"debian-openssl-1.1.x\", \"linux-arm-openssl-1.1.x\", \"linux-musl\"]\n  previewFeatures = [\"orderByRelation\", \"selectRelationCount\"]\n}\n```\n\n```text\n2021-07-21 12:52:58.927 UTC [76] ERROR:  relation \"_prisma_migrations\" does not exist at character 126\n```\n\n```text\ntest-postgres\n```\n\n```text\n5432\n```\n\n```text\nDATABASE_URL=\"postgres://postgres:postgres@localhost:15432/postgres?connect_timeout=300\"\n```\n\n```text\n?connect_timeout=300\n```\n\n```text\nFROM node:16\n```\n\n```text\nFROM node:17\n```\n\n```text\nDATABASE_URL=\"postgresql://root:root@<My IP>:5432/<MY DB Name>\"\n```\n\n========================================\n\nComments:\n- It definitely does the trick. No idea why though.\n- No way, how can this work? And it has 36 upvotes. How adding a connection timeout can solve the problem? Can you explain??\n- It doesn't work with my mariadb database (I'm using ssl). Fails instantly on my device when I add the option and on vercel it always times out instantly, too. However on my device it works if I don't specify anything.\n- We were setting up our backend with prisma in 8 kubernetes pods Since we made so many connections at one go, it was timing out, and only ~4 pods were able to connect at one go. In our case, this param makes a lot sense, since it increased the timeout for connection from 30s to 5mins, and it worked!!!\n- This comment works on my aws RDS mariadb database. Thank you.\n- 17 alphine version isn't working. must be 17 version 😂\n- I spent so much time trying to figure this out. Im on an m2 mac book air, this fixed my issue for good. More people should be able to find this when they need it. thank you so much for this comment.\n- What is \"My IP\"? Your public local IP or 127:0.0.1 ?\n- It's \"Your public local IP\" hope to help u.\n- thanks. it worked for me after I changed to `DATABASE_URL='postgresql:&#47;&#47;username:password@172.20.10.2:543&zwnj;&#8203;2&#47;mydb?schema=public&zwnj;&#8203;'`","metadata":{"transformedAt":"2026-08-18T18:33:14.812Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":157,"estimatedTokens":1130}}11{"id":"stack-69208189","source":"stackoverflow","questionId":69208189,"title":"How do handle enum values in jest test with prisma? Group[] not assignable to Group","tags":["typescript","enums","prisma","ts-jest"],"text":"Title: How do handle enum values in jest test with prisma? Group[] not assignable to Group\nTags: typescript, enums, prisma, ts-jest\nSource: Stack Overflow\n\nQuestion:\nMy `prisma postgresql` schema example\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n uuid String @db.Uuid\n createdat DateTime @default(now()) @db.Timestamp(6)\n updatedat DateTime @updatedAt\n firstname String @db.VarChar\n lastname String @db.VarChar\n email String @unique @db.VarChar\n password String @db.VarChar\n group Group[]\n}\n\nenum Group {\n USER\n ADMIN\n}\n```\n\nThen I have the following `jest` test\n\n```\n/* eslint-disable no-unused-vars */\nimport { create } from '../index';\nimport { prismaMock } from '../../../../../db/singleton';\n\nenum Group {\n USER,\n ADMIN,\n}\n\n// also tried\n/*enum Group {\n USER = 'USER',\n ADMIN = 'ADMIN',\n}*/\n\ntest('should create new user ', async () => {\n try {\n const userModel = {\n id: 1,\n email: 'hello@prisma.io',\n uuid: '65sdf5sa4dfs5sdf54ds5f',\n createdat: new Date(),\n updatedat: new Date(),\n firstname: 'jon',\n lastname: 'doe',\n password: '123456',\n group: [Group.USER],\n };\n\n const demoUser = {\n id: 1,\n email: 'hello@prisma.io',\n uuid: '65sdf5sa4dfs5sdf54ds5f',\n firstname: 'jon',\n lastname: 'doe',\n password: '123456',\n group: [Group.USER],\n };\n\n prismaMock.user.create.mockResolvedValue(userModel);\n\n await expect(create(demoUser)).resolves.toEqual({\n id: 1,\n email: 'hello@prisma.io',\n uuid: '65sdf5sa4dfs5sdf54ds5f',\n createdat: new Date(),\n updatedat: new Date(),\n firstname: 'jon',\n lastname: 'doe',\n password: '123456',\n group: [Group.USER],\n });\n } catch (error) {\n console.log('*****', error);\n }\n});\n```\n\nThat results in the following error:\n\n```\nArgument of type '{ id: number; email: string; uuid: string; createdat: Date; updatedat: Date; firstname: string; lastname: string; nickname: string; password: string; group: Group[]; }' is not assignable to parameter of type 'User | Prisma__UserClient'.\n Type '{ id: number; email: string; uuid: string; createdat: Date; updatedat: Date; firstname: string; lastname: string; nickname: string; password: string; group: Group[]; }' is not assignable to type 'User'.\n Types of property 'group' are incompatible.\n Type 'Group[]' is not assignable to type 'import(\"/example/example-api/node_modules/.prisma/client/index\").Group[]'.\n Type 'Group' is not assignable to type 'import(\"/example/example-api/node_modules/.prisma/client/index\").Group'.ts(2345)\n```\n\nI don't understand `Group[]` is not assignable to type `Group`. In `userModel` I have `group: [Group.USER]`. A user can be a part of many groups. How do i handle this in `typescript` test?\n\n========================================\n\nTop Answer:\nI was getting a weird error in my Jest Tests:\n\n```\nTypeError: Cannot read properties of undefined\n```\n\nto fix it I changed the code from this:\n\n```\nimport { Group } from 'prisma/schema'\n\nconst valuePayload = {\n resource: Group.USER\n}\n```\n\nto this:\n\n```\nimport { Group } from 'prisma/schema'\n\nconst valuePayload = {\n resource: \"USER\" as Group\n}\n```\n\n========================================\n\nCode:\n```text\nmodel User {\n  id         Int          @id @default(autoincrement())\n  uuid       String       @db.Uuid\n  createdat DateTime     @default(now()) @db.Timestamp(6)\n  updatedat DateTime     @updatedAt\n  firstname String       @db.VarChar\n  lastname  String       @db.VarChar\n  email      String       @unique @db.VarChar\n  password   String       @db.VarChar\n  group      Group[]\n}\n\nenum Group {\n  USER\n  ADMIN\n}\n```\n\n```text\n/* eslint-disable no-unused-vars */\nimport { create } from '../index';\nimport { prismaMock } from '../../../../../db/singleton';\n\nenum Group {\n  USER,\n  ADMIN,\n}\n\n// also tried\n/*enum Group {\n  USER = 'USER',\n  ADMIN = 'ADMIN',\n}*/\n\n\ntest('should create new user ', async () => {\n  try {\n    const userModel = {\n      id: 1,\n      email: 'hello@prisma.io',\n      uuid: '65sdf5sa4dfs5sdf54ds5f',\n      createdat: new Date(),\n      updatedat: new Date(),\n      firstname: 'jon',\n      lastname: 'doe',\n      password: '123456',\n      group: [Group.USER],\n    };\n\n    const demoUser = {\n      id: 1,\n      email: 'hello@prisma.io',\n      uuid: '65sdf5sa4dfs5sdf54ds5f',\n      firstname: 'jon',\n      lastname: 'doe',\n      password: '123456',\n      group: [Group.USER],\n    };\n\n    prismaMock.user.create.mockResolvedValue(userModel);\n\n    await expect(create(demoUser)).resolves.toEqual({\n      id: 1,\n      email: 'hello@prisma.io',\n      uuid: '65sdf5sa4dfs5sdf54ds5f',\n      createdat: new Date(),\n      updatedat: new Date(),\n      firstname: 'jon',\n      lastname: 'doe',\n      password: '123456',\n      group: [Group.USER],\n    });\n  } catch (error) {\n    console.log('*****', error);\n  }\n});\n```\n\n```text\nArgument of type '{ id: number; email: string; uuid: string; createdat: Date; updatedat: Date; firstname: string; lastname: string; nickname: string; password: string; group: Group[]; }' is not assignable to parameter of type 'User | Prisma__UserClient<User>'.\n  Type '{ id: number; email: string; uuid: string; createdat: Date; updatedat: Date; firstname: string; lastname: string; nickname: string; password: string; group: Group[]; }' is not assignable to type 'User'.\n    Types of property 'group' are incompatible.\n      Type 'Group[]' is not assignable to type 'import(\"/example/example-api/node_modules/.prisma/client/index\").Group[]'.\n        Type 'Group' is not assignable to type 'import(\"/example/example-api/node_modules/.prisma/client/index\").Group'.ts(2345)\n```\n\n```text\nprisma postgresql\n```\n\n```text\njest\n```\n\n```text\nGroup[]\n```\n\n```text\nGroup\n```\n\n```text\nuserModel\n```\n\n```text\ngroup: [Group.USER]\n```\n\n```text\ntypescript\n```\n\n```text\nimport { Group } from '@prisma/client';\n\nconst userModel = {\n      id: 1,\n      email: 'hello@prisma.io',\n      uuid: '65sdf5sa4dfs5sdf54ds5f',\n      createdat: new Date(),\n      updatedat: new Date(),\n      firstname: 'jon',\n      lastname: 'doe',\n      password: '123456',\n      group: [Group.USER],\n};\n```\n\n```text\nTypeError: Cannot read properties of undefined\n```\n\n```text\nimport { Group } from 'prisma/schema'\n\nconst valuePayload = {\n  resource: Group.USER\n}\n```\n\n```text\nimport { Group } from 'prisma/schema'\n\nconst valuePayload = {\n  resource: \"USER\" as Group\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.813Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":281,"estimatedTokens":1559}}12{"id":"stack-67746885","source":"stackoverflow","questionId":67746885,"title":"@prisma/client did not initialize yet. Please run \"prisma generate\" and try to import it again","tags":["node.js","docker","kubernetes","prisma"],"text":"Title: @prisma/client did not initialize yet. Please run \"prisma generate\" and try to import it again\nTags: node.js, docker, kubernetes, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using prisma, postgres, docker, kubernets.\n\n**npx prisma migrate dev** working.\n\nand **npx prisma generate** produce below output:\n\n```\n✔ Generated Prisma Client (2.23.0) to ./node_modules/@prisma/client in 68ms\nYou can now start using Prisma Client in your code. Reference: https://pris.ly/d/client\n\nimport { PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n```\n\nbut when I tried to use in my route file produce the error:\n\nnew-route.ts\n\n```\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n```\n\nmy docker file:\n\n```\nFROM node:alpine\n\nWORKDIR /app\nCOPY package.json .\nRUN npm install --only=prod\nCOPY . .\n\nCMD [\"npm\", \"start\"]\n```\n\n========================================\n\nTop Answer:\nJust remove the following line from the `schema.prisma` file:\n\n```\noutput = \"../generated/prisma\"\n```\n\nand execute:\n\n```\nnpx prisma generate\n```\n\n========================================\n\nCode:\n```text\n✔ Generated Prisma Client (2.23.0) to ./node_modules/@prisma/client in 68ms\nYou can now start using Prisma Client in your code. Reference: https://pris.ly/d/client\n\nimport { PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n```\n\n```text\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n```\n\n```text\nFROM node:alpine\n\nWORKDIR /app\nCOPY package.json .\nRUN npm install --only=prod\nCOPY . .\n\nCMD [\"npm\", \"start\"]\n```\n\n```text\nkubectl exec -it pod_name sh\nnpx prisma generate\n```\n\n```text\nschema.prisma\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpm start\n```\n\n```text\n# Build image\nFROM node:16.13-alpine as builder\nWORKDIR /app\n\n# Not sure if you will need this\n# RUN apk add --update openssl\n\nCOPY package*.json ./\nRUN npm ci --quiet\n\nCOPY ./prisma prisma\nCOPY ./src src\nRUN npm run build\n\n# Production image\n\nFROM node:16.13-alpine\nWORKDIR /app\nENV NODE_ENV production\n\nCOPY package*.json ./\nRUN npm ci --only=production --quiet\n\nCOPY --chown=node:node --from=builder /app/prisma /app/prisma\nCOPY --chown=node:node --from=builder /app/src /app/src\n\nUSER node\n\nEXPOSE 8080\nCMD [\"node\", \"src/index.js\"]\n```\n\n```text\n{\n  \"name\": \"example\",\n  \"description\": \"\",\n  \"version\": \"0.1.0\",\n  \"scripts\": {\n    \"generate\": \"npx prisma generate\",\n    \"deploy\": \"npx prisma migrate deploy\",\n    \"dev\": \"npm run generate && nodemon --watch \\\"src/**\\\" --ext \\\"js,json\\\" --exec \\\"node src/index.js\\\"\",\n    \"build\": \"npm run generate\",\n    \"start\": \"npm run build && node build/index.js\"\n  },\n  \"prisma\": {\n    \"schema\": \"prisma/schema.prisma\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"^3.6.0\"\n  },\n  \"devDependencies\": {\n    \"@tsconfig/node16\": \"^1.0.2\",\n    \"@types/node\": \"^16.11.12\",\n    \"nodemon\": \"^2.0.15\",\n    \"prisma\": \"^3.6.0\"\n  }\n}\n```\n\n```text\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: EXAMPLE\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: EXAMPLE\n  strategy:\n    rollingUpdate:\n      maxSurge: 100%\n      maxUnavailable: 0\n    type: RollingUpdate\n  template:\n    metadata:\n      labels:\n        app: EXAMPLE\n    spec:\n      containers:\n        image: DOCKER_IMAGE\n        imagePullPolicy: IfNotPresent\n        name: SERVICE_NAME\n        ports:\n        - containerPort: 8080\n          name: http\n          protocol: TCP\n      initContainers:\n      - command:\n        - npm\n        - run\n        - deploy\n        image: DOCKER_IMAGE\n        imagePullPolicy: IfNotPresent\n        name: database-migrate-deploy\n```\n\n```text\nprisma migrate deploy\n```\n\n```text\nWORKDIR /app\nCOPY package*.json .\nCOPY prisma ./prisma/ \nRUN npm install --only=prod\n```\n\n```text\nprisma\n```\n\n```text\nschema.prisma\n```\n\n```text\nnode_modules/\n!nodes_modules/.prisma\n```\n\n```text\n.prisma\n```\n\n```text\n.dockerignore\n```\n\n```text\nRUN npx prisma generate\n```\n\n```text\nprisma generate\n```\n\n```text\n\"start\": \"npx prisma generate && nodemon server.ts\"\n```\n\n```text\n\"start\": \"npx prisma db push && npx prisma generate && node ./build/server.js\"\n```\n\n```text\nstart\n```\n\n```text\nscripts\n```\n\n```text\npackage.json\n```\n\n```text\nvolumes:\n  - /app/prisma\n```\n\n```text\nversion: \"3\"\n\nservices:\n  web:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    container_name: web\n    restart: always\n    volumes:\n      - ./:/app\n      - /app/node_modules\n      - /app/.next\n      - /app/prisma\n    ports:\n      - 3000:3000\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\n...\n\"vercel-build\": \"npx prisma generate && next build\"\n...\n```\n\n```text\n\"@prisma/client\"\n```\n\n```text\n\"@prisma/client/edge\"\n```\n\n```text\n\"../../prisma/generated/client/edge\"\n```\n\n```text\nnext js\n```\n\n```text\nPrisma\n```\n\n```text\nVercel\n```\n\n```text\n\"postinstall\":\"npx prisma generate\"\n```\n\n```text\npackage.json\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"node_modules/.prisma/client\"\n}\n```\n\n```text\noutput\n```\n\n```text\nschema.prisma\n```\n\n```text\nmodel matches {\n  id          Int    @id @default(autoincrement())\n  name        String    \n  matchType   String    \n  matchStatus MatchStatus    \n  matchResult String   \n  isDeleted   Boolean   @default(false)\n  createdAt   DateTime  @default(now())\n  modifiedAt  DateTime  @default(now())\n  createdBy   Int\n  modifiedBy  Int\n}\n```\n\n```text\n\"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n    \"start\": \"npx prisma generate && nodemon app.js\"\n  },\n```\n\n```text\n\"postinstall\": \"prisma generate --schema=<Enter the location to your prisma.schema file>\"\n```\n\n```text\n\"^ Error: @prisma/client did not initialize yet. Please run \"prisma generate\" and try to import it again. In case this error is unexpected for you\"\n```\n\n```text\nCOPY package*.json ./\nRUN npm ci\nCOPY prisma ./prisma/\nCOPY ..\nRUN npx prisma generate\nRUN npm run build\nCMD [\"npm\",\"run\",\"start\"]\n```\n\n```text\noutput   = \"../generated/prisma\"\n```\n\n```bash\nnpx prisma generate\n```\n\n```text\nschema.prisma\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"../generated/prisma\"\n}\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"../node_modules/.prisma/client\"\n}\n```\n\n```text\nIn schema.prisma file\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"../src/generated/prisma\" // notice that\n}\n```\n\n```text\nimport { PrismaClient } from \"../src/generated/prisma\"; // notice that\nBoth will be the same.\n```\n\n```text\noutput   = \"../app/generated/prisma\"\n```\n\n```text\nI change the below like this. \n\nimport { PrismaClient } from '@prisma/client'\nimport { PrismaClient } from \"../../generated/prisma\";\n```\n\n========================================\n\nComments:\n- I think if you copy `COPY prisma .&#47;prisma&#47;` that should work. But I'm a few steps behind you as I can't get the `npx prisma migrate dev` to work with the error message: `Error: P1001: Can't reach database server at auth-postgres-srv.default.svc.cluster.local:5432`\n- Just wanted to add my 2 cents to this. Recently spent half a day trying to figure out why my schema changes weren't being reflected when calling Prisma service. Turns out I had to restart the node environment or as I like to do it just restart the whole IDE and voila the changes start reflecting.\n- copy this generator client { provider = \"prisma-client-js\" } the -js make total difference, this solve my problem and then run npx prisma generate agains\n- The solution given by Rafiq to run `npx prisma generate` in the pod is likely a bad one - next time the pod is restarted it will fail again. Just copy the `prisma` dir when building your image\n- how do you run prisma migrations and seed for production? you just ran generate in Dockerfile\n- thanks for this, very useful. However, can you explain why you copy your `node_modules` from your build image? Doesn't that overwrite your lean production `node_modules` with all the dev dependencies and bloat your final image?\n- @JPLew You're absolutely correct, that statement should not be there. I'm updating my answer.\n- @markokraljevic As far as i know `npx prisma generate` only creates the `.&#47;prisma&#47;generated` directory. So it makes perfect sense to have that in the Dockerfile.\n- And I am facing this error , ``` Error: Unknown binaryTarget linux-arm64-openssl-undefined and no custom engine files were provided`. I have added the binary target in schema.prisma but I couldn’t resolve the error.` binaryTargets = [\"native\", \"rhel-openssl-1.0.x\"]```\n- Thank you! This is the correct answer, simply copy this folder before running install and it will work\n- I was confused why I was receiving the error even though I was copying the `prisma` folder in my Dockerfile. But as you pointed out, it needs to be copied *before* running `npm install`\n- No need to generate if you copy prisma folder before running `npm install`\n- using \"prisma generate\" requires to have the development npm dependencies which is not good for production build, how do you handle this? @Codebling - you want all to start from a plain base docker image and do not import anything from outside.\n- @IvailoBardarov commands run with `npx` do not get installed in the local folder. You can use a build stage if you want to build a docker image and are worried about including more than needed. I am happy to try to help you with a questions about npm, Docker and/or avoiding dev dependencies, feel free to ask a question and link it here\n- @Codebling you are absolutely right, by using npx we can generate the client without installing the package. Thank you for pointing it!\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Encountering this error in mid 2025, the output and with that a shadow database will be mandatory in Prisma 7.0.0.\n- Can you explain why removing it solves the problem?\n- Appreciate your comment, the only thing that had worked!\n- OMG! THANK YOU! Why isn't this documented! Nowhere in the docs does it mention to omit it or set it to the value `..&#47;node_modules&#47;.prisma&#47;client`. The documented default value `node_modules&#47;.prisma&#47;client` (source) is incorrect, because it outputs to the `.&#47;prisma` folder🤦 I found it also solves the \"PrismaClient is unable to be run in the browser\" error. As @vu-tung-lam mentions, it has to be set come `v7.0.0`.\n- you save my day!\n- This should be the definite answer.\n- THIS SOLUTION DESERVES A TROPHY. IT'S THE ONLY THING THAT WORKED FOR ME AFTER THREE DAYS OF DEBUGGING... AND IT'S SIMPLE!\n- solved it with this method, idk why but it works well for me after debugging an hour\n- The issue is with how your importing Prisma-client from import { PrismaClient } from \"@prisma/client\"; to import { PrismaClient } from '../prisma/generated/clientPg' This solved my issue\n- you are legendary bruh, thanks\n- The only comment that has worked so far for me. thanks so much\n- this is going to sound crazy i kept the output line and same import shit in the db file import { PrismaClient } from \"@prisma/client\"; const prisma = new PrismaClient(); export default prisma; i was able to run 2 successful migrations before it crashed out of nowhere. first it was due to the binaries issues fixed that one but now it due to @prisma/client did not initialize yet mind u i have generated the client already\n- Yes. They recently deprecate the behavior of omitting \"output\" there (and \"output\" will be required in 7.0.0), but they provided a broken example in the docs where they specified output elsewhere like src/generated. How dare they? Changed as you suggested and it worked! Thanks!\n- It's mad how this hasn't been officially documented as a step to do! I can agree, either omitting \"output\" or setting it to the value `..&#47;node_modules&#47;.prisma&#47;client` works, but, as @vu-tung-lam mentions, it is a required field come `v7.0.0`.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.813Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":54,"totalLines":469,"estimatedTokens":3097}}13{"id":"stack-70748250","source":"stackoverflow","questionId":70748250,"title":"Prisma, select row from table 1, depending on the latest foreign key in table 2","tags":["prisma"],"text":"Title: Prisma, select row from table 1, depending on the latest foreign key in table 2\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nApologies for the bad title, struggling to think of another.\n\nCurrently, I have 2 tables, `publication` and `publicationStatus`.\n\nA publication will looking something like:\n\n```\n{\n \"id\": \"ckyil950d00027v2str5ljo7h\",\n \"url_slug\": \"ckyil950e00037v2s4mqxvaho\",\n \"type\": \"PEER_REVIEW\",\n \"title\": \"Intersting review\",\n \"content\": \"Content is optional at this stage\",\n \"doi\": \"1093/ajae/aaq063\",\n \"createdBy\": \"test-user-1\",\n \"createdAt\": \"2022-01-17T11:12:50.845Z\",\n \"updatedAt\": \"2022-01-17T11:12:50.847Z\",\n \"publicationStatus\": [\n {\n \"status\": \"LIVE\",\n \"createdAt\": \"2022-01-19T11:12:50.846Z\",\n \"id\": \"ckyil950e00047v2sx4urbfte\"\n },\n {\n \"status\": \"DRAFT\",\n \"createdAt\": \"2022-01-17T11:12:50.846Z\",\n \"id\": \"ckyil950e00047v2sx4urbfth\"\n }\n ],\n \"user\": {\n \"id\": \"test-user-1\",\n \"firstName\": \"Test\",\n \"lastName\": \"User 1\"\n }\n}\n```\n\nWhere `publication` has a 1 to many relationship with `publicationStatus`.\n\nWhat I need to do is a `find` query where it only returns a `publication` if the **latest** `publicationStatus` for that `publication`, has a `status` of `LIVE`.\n\nAny ideas?\n\n**Edit:**\nThe closest I could come to is this **psuedo** code:\n\n```\nawait prisma.publication.findFirst({\n where: {\n id,\n publicationStatus: {\n where: {\n status: 'LIVE'\n },\n take: 1,\n orderBy: {\n createdAt: 'desc'\n }\n },\n }\n});\n```\n\nThis code does **not** work, but demonstrates a picture of what I'm trying to achieve.\n\n========================================\n\nCode:\n```json\n{\n    \"id\": \"ckyil950d00027v2str5ljo7h\",\n    \"url_slug\": \"ckyil950e00037v2s4mqxvaho\",\n    \"type\": \"PEER_REVIEW\",\n    \"title\": \"Intersting review\",\n    \"content\": \"Content is optional at this stage\",\n    \"doi\": \"1093/ajae/aaq063\",\n    \"createdBy\": \"test-user-1\",\n    \"createdAt\": \"2022-01-17T11:12:50.845Z\",\n    \"updatedAt\": \"2022-01-17T11:12:50.847Z\",\n    \"publicationStatus\": [\n        {\n            \"status\": \"LIVE\",\n            \"createdAt\": \"2022-01-19T11:12:50.846Z\",\n            \"id\": \"ckyil950e00047v2sx4urbfte\"\n        },\n        {\n            \"status\": \"DRAFT\",\n            \"createdAt\": \"2022-01-17T11:12:50.846Z\",\n            \"id\": \"ckyil950e00047v2sx4urbfth\"\n        }\n    ],\n    \"user\": {\n        \"id\": \"test-user-1\",\n        \"firstName\": \"Test\",\n        \"lastName\": \"User 1\"\n    }\n}\n```\n\n```js\nawait prisma.publication.findFirst({\n    where: {\n        id,\n        publicationStatus: {\n            where: {\n                status: 'LIVE'\n            },\n            take: 1,\n            orderBy: {\n                createdAt: 'desc'\n            }\n        },\n    }\n});\n```\n\n```text\npublication\n```\n\n```text\npublicationStatus\n```\n\n```text\npublication\n```\n\n```text\npublicationStatus\n```\n\n```text\nfind\n```\n\n```text\npublication\n```\n\n```text\npublicationStatus\n```\n\n```text\npublication\n```\n\n```text\nstatus\n```\n\n```text\nLIVE\n```\n\n```js\nlet publication = await prisma.publication.findFirst({\n        where: {\n            id\n        },\n        include: {\n            publicationStatus: {\n                orderBy: {\n                    createdAt: 'desc'\n                },\n                take: 1\n            }\n        }\n    });\n\n    // check publication.publicationStatus[0].status and handle appropriately\n```\n\n```text\npublicationStatus\n```\n\n```text\npublication\n```\n\n```text\nstatus\n```\n\n```text\nqueryRaw\n```\n\n========================================\n\nComments:\n- I see that the `where` condition has the publication's `id` field. Does that mean you're querying a *single* publication, by its `id`? In addition, what is your desired returned data in case the latest `publicationStatus` is not `LIVE`?\n- So if the `publicationStatus` is not `LIVE`, a `null` is fine. Right now it's for a single `id`, the API would return `null` or the object. However, will need something similar for my `GET &#47;publications` where it will return all (with pagination) for publications that are `LIVE`\n- Hi, thanks for this. We decided to take an even simpler approach and add a `currentStatus` field to `publications`, that should update whenever the `publicationStatus` one is.\n- Great, glad to see you found a suitable workaround :D","metadata":{"transformedAt":"2026-08-18T18:33:14.813Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":202,"estimatedTokens":1051}}14{"id":"stack-70175448","source":"stackoverflow","questionId":70175448,"title":"Prisma deleteMany with a list of IDs","tags":["javascript","prisma"],"text":"Title: Prisma deleteMany with a list of IDs\nTags: javascript, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm wondering if there is a way in the Prisma Client to batch delete database records by id.\n\nSomething like this doesn't seem to exist:\n\n```\nconst idsToDelete = [5, 29, 255]\n\nprisma.post.deleteMany({\n where: {\n id: {\n equals: idsToDelete\n }\n }\n})\n```\n\nThe docs allude to the concept of Scalar List Filters, but this doesn't seem to be supported for numeric lists or perhaps isn't supported in `deleteMany`.\n\nUnder the hood, I'm hoping for a SQL `DELETE ... WHERE IN` clause. I'd prefer not to:\n\n- Spin up a bunch of individual JS promises\n\n- Use database-specific Prisma features (ok if it's not supported in MongoDB)\n\n- Write SQL directly\n\n========================================\n\nCode:\n```text\nconst idsToDelete = [5, 29, 255]\n\nprisma.post.deleteMany({\n    where: {\n        id: {\n            equals: idsToDelete\n        }\n    }\n})\n```\n\n```text\ndeleteMany\n```\n\n```text\nDELETE ... WHERE IN\n```\n\n```text\nwhere: {\n        id: {\n            in: idsToDelete\n        }\n    }\n```\n\n```text\nin\n```\n\n========================================\n\nComments:\n- Thanks, that's exactly what I need. Do you have a link to where it is documented?\n- No problem. The client API reference is here: prisma.io/docs/reference/api-reference/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.813Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":71,"estimatedTokens":332}}15{"id":"stack-76336930","source":"stackoverflow","questionId":76336930,"title":"Fetching Next.js API Route in the app directory gives 404 Not Found","tags":["javascript","reactjs","next.js","prisma"],"text":"Title: Fetching Next.js API Route in the app directory gives 404 Not Found\nTags: javascript, reactjs, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am struggling with Next.js 13's `app` routing. It always gives me a 404 Not Found when I try to access, for example from Postmann.\n\nI have this file structure:\n\nhttps://i.sstatic.net/ZWrlb.png\n\nAnd for example, one of my API files is:\n\n```\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nexport default async function all(req, res) {\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' });\n }\n\n try {\n // Get all admins using Prisma\n const admins = await prisma.admin.findMany();\n\n return res.status(200).json(admins);\n }\n catch (error) {\n return res.status(500).json({ error: 'Failed to get admins' });\n }\n}\n```\n\nWhen I send a `GET localhost:3000/api/admin/all` it always responds with a 404. Couldn't find where is the error.\n\nI tried other file or folder namings. Calling from my own app, using the curl command, or using Postman. My other API routes give the same 404.\n\n========================================\n\nTop Answer:\nIn addition to Youssouf's answer (which I found very helpful), if you have problems getting the content of `request.body`, use `const body = await request.json()` to get the body.\n\nhttps://developer.mozilla.org/en-US/docs/Web/API/Request/json\n\n========================================\n\nCode:\n```text\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nexport default async function all(req, res) {\n    if (req.method !== 'GET') {\n        return res.status(405).json({ error: 'Method not allowed' });\n    }\n\n    try {\n        // Get all admins using Prisma\n        const admins = await prisma.admin.findMany();\n\n        return res.status(200).json(admins);\n    }\n    catch (error) {\n        return res.status(500).json({ error: 'Failed to get admins' });\n    }\n}\n```\n\n```text\napp\n```\n\n```text\nGET localhost:3000/api/admin/all\n```\n\n```js\nexport async function GET(request) {}\n```\n\n```js\n// Notice from where NextResponse is imported:\nimport { NextResponse } from \"next/server\";\n\nimport { PrismaClient } from \"@prisma/client\";\n\nconst prisma = new PrismaClient();\n\n// Notice the function definition:\nexport async function GET(req) {\n  return NextResponse.json(\n    { error: \"Method not allowed\" },\n    {\n      status: 405\n    }\n  );\n}\n\n// Notice the function definition:\nexport async function POST(req) {\n  try {\n    // Get all admins using Prisma\n    const admins = await prisma.admin.findMany();\n\n    return NextResponse.json(admins, {\n      status: 200,\n    });\n  } catch (error) {\n    return NextResponse.json(\n      { error: \"Failed to get admins\" },\n      {\n        status: 500,\n      }\n    );\n  }\n}\n```\n\n```text\nroute.js\n```\n\n```text\napp/api/admin/all.js\n```\n\n```text\napp/api/admin/route.js\n```\n\n```text\n/api/admin\n```\n\n```text\nGET\n```\n\n```text\nPOST\n```\n\n```text\nPUT\n```\n\n```text\nPATCH\n```\n\n```text\nrequest.body\n```\n\n```text\nconst body = await request.json()\n```\n\n```js\n/** @type {import('next').NextConfig} */\nconst nextConfig = {\n  eslint: {\n    ignoreDuringBuilds: true,\n  },\n  images: { unoptimized: true },\n};\n\nmodule.exports = nextConfig;\n```\n\n```text\napp\n```\n\n```text\napp\n```\n\n```text\napp/api/test/route.ts\n```\n\n```text\napp/api/test/route.js\n```\n\n```text\nnext.config.js\n```\n\n```text\n\"output\": \"export\"\n```\n\n```text\nnext.config.js\n```\n\n```text\nnext.config.js\n```\n\n========================================\n\nComments:\n- Thanks, this has been very helpful. I was following the official docs for setting up Vercel Postgres, and the example filenames and paths do not mention this \"automagic\" convention at all. vercel.com/docs/storage/vercel-postgres/quickstart","metadata":{"transformedAt":"2026-08-18T18:33:14.813Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":209,"estimatedTokens":938}}16{"id":"stack-73117939","source":"stackoverflow","questionId":73117939,"title":"Unknown binaryTarget debian-openssl-3.0.x and no custom binaries were provided error Command failed with exit code 1","tags":["openssl","prisma"],"text":"Title: Unknown binaryTarget debian-openssl-3.0.x and no custom binaries were provided error Command failed with exit code 1\nTags: openssl, prisma\nSource: Stack Overflow\n\nQuestion:\nIs there any way I can solve this problem? I recently updated to Ubuntu 22.04\nGetting the problem while using Prisma.I can't run my project. I have use \"@prisma/client\": \"2.20.1\"\n\nError: Unknown binaryTarget debian-openssl-3.0.x and no custom binaries were provided\nerror Command failed with exit code 1.\n\n========================================\n\nTop Answer:\nRun the following commands in project\n\n```\nnpm install prisma --save-dev\n\nnpm install @prisma/client@dev prisma@dev\n```\n\n========================================\n\nCode:\n```text\n3.13.0\n```\n\n```text\n3.13.0\n```\n\n```text\nnpm install prisma --save-dev\n\nnpm install @prisma/client@dev prisma@dev\n```\n\n```text\nnode -v\n```\n\n```text\nplugins: [\n    new CopyPlugin({\n      patterns: [\n        { from: './node_modules/.prisma/client/schema.prisma', to: './build/src' }, // you may need to change `to` here.\n        { from: './node_modules/.prisma/client/libquery_engine-rhel-openssl-3.0.x.so.node', to: './build/src' }, // you may need to change `to` here.\n      ],\n    }),\n```\n\n```text\n'./build/src'\n```\n\n```text\ngenerator client {\n  provider      = \"prisma-client-js\"\n  binaryTargets = [\"native\", \"debian-openssl-1.1.x\", \"debian-openssl-3.0.x\"]\n}\n```\n\n========================================\n\nComments:\n- Thank you so much. Saved me a few hours of debugging!\n- This sucks for those who cannot upgrade\n- Thank you! This worked for me and I am appreciative. As an answer however, it does leave a bit to be desired. If you have the time, would you consider adding some explanation as far as what we are doing with these commands and why they solve the issue?","metadata":{"transformedAt":"2026-08-18T18:33:14.813Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":447}}17{"id":"stack-50456780","source":"stackoverflow","questionId":50456780,"title":"Run MySQL on Port 3307 Using Docker Compose","tags":["mysql","docker","docker-compose","prisma"],"text":"Title: Run MySQL on Port 3307 Using Docker Compose\nTags: mysql, docker, docker-compose, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to create multiple Prisma database services on a single machine. I have been unable to create a MySQL database on a port other than 3306 using Docker Compose. \n\ndocker-compose.yml \n\n```\nversion: '3'\nservices:\nhackernews:\n image: prismagraphql/prisma:1.8\n restart: always\n ports:\n - \"${CLIENT_PORT}:${INTERNAL_PORT}\"\n environment:\n PRISMA_CONFIG: |\n port: $INTERNAL_PORT\n managementApiSecret: $PRISMA_MANAGEMENT_API_SECRET\n databases:\n default:\n connector: mysql\n host: mysql\n port: $SQL_INTERNAL_PORT\n user: root\n password: $SQL_PASSWORD\n migrations: true\nmysql:\n image: mysql:5.7\n restart: always\n environment:\n MYSQL_ROOT_PASSWORD: $SQL_PASSWORD\n volumes:\n - ./custom/:/etc/mysql/conf.d/my.cnf\n - mysql:/var/lib/mysql\nvolumes:\nmysql:\n```\n\ndocker-compose.override.yml \n\n```\nversion: '3'\nservices:\nmysql:\n expose:\n - \"${SQL_INTERNAL_PORT}\"\n ports:\n - \"${SQL_CLIENT_PORT}:${SQL_INTERNAL_PORT}\"\n```\n\nError:\n\n```\nhackernews_1 | Exception in thread \"main\" java.sql.SQLTransientConnectionException: database - Connection is not available, request timed out after 5008ms.\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:548)\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:186)\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:145)\nhackernews_1 | at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:83)\nhackernews_1 | at slick.jdbc.hikaricp.HikariCPJdbcDataSource.createConnection(HikariCPJdbcDataSource.scala:18)\nhackernews_1 | at slick.jdbc.JdbcBackend$BaseSession.(JdbcBackend.scala:439)\nhackernews_1 | at slick.jdbc.JdbcBackend$DatabaseDef.createSession(JdbcBackend.scala:47)\nhackernews_1 | at slick.jdbc.JdbcBackend$DatabaseDef.createSession(JdbcBackend.scala:38)\nhackernews_1 | at slick.basic.BasicBackend$DatabaseDef.acquireSession(BasicBackend.scala:218)\nhackernews_1 | at slick.basic.BasicBackend$DatabaseDef.acquireSession$(BasicBackend.scala:217)\nhackernews_1 | at slick.jdbc.JdbcBackend$DatabaseDef.acquireSession(JdbcBackend.scala:38)\nhackernews_1 | at slick.basic.BasicBackend$DatabaseDef$$anon$2.run(BasicBackend.scala:239)\nhackernews_1 | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\nhackernews_1 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\nhackernews_1 | at java.lang.Thread.run(Thread.java:748)\nhackernews_1 | Caused by: java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=mysql)(port=3307)(type=master) : Connection refused (Connection refused)\nhackernews_1 | at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:161)\nhackernews_1 | at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.connException(ExceptionMapper.java:79)\nhackernews_1 | at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1040)\nhackernews_1 | at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:490)\nhackernews_1 | at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:144)\nhackernews_1 | at org.mariadb.jdbc.Driver.connect(Driver.java:90)\nhackernews_1 | at slick.jdbc.DriverDataSource.getConnection(DriverDataSource.scala:101)\nhackernews_1 | at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:341)\nhackernews_1 | at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:193)\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:430)\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool.access$500(HikariPool.java:64)\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:570)\nhackernews_1 | at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:563)\nhackernews_1 | at java.util.concurrent.FutureTask.run(FutureTask.java:266)\n```\n\ndocker ps \n\n```\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\nab721996469d mysql:5.7 \"docker-entrypoint.s…\" 42 minutes ago Up 55 seconds 3306/tcp, 0.0.0.0:3307->3307/tcp two_mysql_1\n7aab98e2b8d7 prismagraphql/prisma:1.8 \"/bin/sh -c /app/sta…\" 2 hours ago Restarting (1) Less than a second ago two_hackernews_1\n```\n\n.env\n\n```\nSQL_PASSWORD=myuniquepassword\nSQL_INTERNAL_PORT=3307\nSQL_CLIENT_PORT=3307\n```\n\n========================================\n\nTop Answer:\nIn my case I could not change the Mysql port rather than 3306 until I add `MYSQL_TCP_PORT`\n\nSo sample:\n\n```\nversion: '3.8'\n\nvolumes:\n mysql_data:\n driver: local\n\nservices:\n mysql:\n image: mysql:5.7\n volumes:\n - mysql_data:/var/lib/mysql\n environment:\n MYSQL_ROOT_PASSWORD: root\n MYSQL_DATABASE: keycloak\n MYSQL_USER: keycloak\n MYSQL_PASSWORD: password\n MYSQL_TCP_PORT: 3307\n ports:\n - 3307:3307\n expose:\n - 3307\n keycloak:\n image: quay.io/keycloak/keycloak:latest\n environment:\n DB_VENDOR: MYSQL\n DB_ADDR: mysql\n DB_DATABASE: keycloak\n DB_USER: keycloak\n DB_PASSWORD: password\n DB_PORT: 3307\n KEYCLOAK_USER: admin\n KEYCLOAK_PASSWORD: Pa55w0rd\n # Uncomment the line below if you want to specify JDBC parameters. The parameter below is just an example, and it shouldn't be used in production without knowledge. It is highly recommended that you read the MySQL JDBC driver documentation in order to use it.\n #JDBC_PARAMS: \"connectTimeout=30000\"\n ports:\n - 8040:8080\n depends_on:\n - mysql\n```\n\n========================================\n\nCode:\n```text\nversion: '3'\nservices:\nhackernews:\n    image: prismagraphql/prisma:1.8\n    restart: always\n    ports:\n    - \"${CLIENT_PORT}:${INTERNAL_PORT}\"\n    environment:\n    PRISMA_CONFIG: |\n        port: $INTERNAL_PORT\n        managementApiSecret: $PRISMA_MANAGEMENT_API_SECRET\n        databases:\n        default:\n            connector: mysql\n            host: mysql\n            port: $SQL_INTERNAL_PORT\n            user: root\n            password: $SQL_PASSWORD\n            migrations: true\nmysql:\n    image: mysql:5.7\n    restart: always\n    environment:\n    MYSQL_ROOT_PASSWORD: $SQL_PASSWORD\n    volumes:\n    - ./custom/:/etc/mysql/conf.d/my.cnf\n    - mysql:/var/lib/mysql\nvolumes:\nmysql:\n```\n\n```text\nversion: '3'\nservices:\nmysql:\n    expose:\n    - \"${SQL_INTERNAL_PORT}\"\n    ports:\n    - \"${SQL_CLIENT_PORT}:${SQL_INTERNAL_PORT}\"\n```\n\n```text\nhackernews_1  | Exception in thread \"main\" java.sql.SQLTransientConnectionException: database - Connection is not available, request timed out after 5008ms.\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:548)\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:186)\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:145)\nhackernews_1  |     at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:83)\nhackernews_1  |     at slick.jdbc.hikaricp.HikariCPJdbcDataSource.createConnection(HikariCPJdbcDataSource.scala:18)\nhackernews_1  |     at slick.jdbc.JdbcBackend$BaseSession.<init>(JdbcBackend.scala:439)\nhackernews_1  |     at slick.jdbc.JdbcBackend$DatabaseDef.createSession(JdbcBackend.scala:47)\nhackernews_1  |     at slick.jdbc.JdbcBackend$DatabaseDef.createSession(JdbcBackend.scala:38)\nhackernews_1  |     at slick.basic.BasicBackend$DatabaseDef.acquireSession(BasicBackend.scala:218)\nhackernews_1  |     at slick.basic.BasicBackend$DatabaseDef.acquireSession$(BasicBackend.scala:217)\nhackernews_1  |     at slick.jdbc.JdbcBackend$DatabaseDef.acquireSession(JdbcBackend.scala:38)\nhackernews_1  |     at slick.basic.BasicBackend$DatabaseDef$$anon$2.run(BasicBackend.scala:239)\nhackernews_1  |     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\nhackernews_1  |     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\nhackernews_1  |     at java.lang.Thread.run(Thread.java:748)\nhackernews_1  | Caused by: java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=mysql)(port=3307)(type=master) : Connection refused (Connection refused)\nhackernews_1  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:161)\nhackernews_1  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.connException(ExceptionMapper.java:79)\nhackernews_1  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1040)\nhackernews_1  |     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:490)\nhackernews_1  |     at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:144)\nhackernews_1  |     at org.mariadb.jdbc.Driver.connect(Driver.java:90)\nhackernews_1  |     at slick.jdbc.DriverDataSource.getConnection(DriverDataSource.scala:101)\nhackernews_1  |     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:341)\nhackernews_1  |     at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:193)\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:430)\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool.access$500(HikariPool.java:64)\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:570)\nhackernews_1  |     at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:563)\nhackernews_1  |     at java.util.concurrent.FutureTask.run(FutureTask.java:266)\n```\n\n```text\nCONTAINER ID        IMAGE                      COMMAND                  CREATED             STATUS                                  PORTS                              NAMES\nab721996469d        mysql:5.7                  \"docker-entrypoint.s…\"   42 minutes ago      Up 55 seconds                           3306/tcp, 0.0.0.0:3307->3307/tcp   two_mysql_1\n7aab98e2b8d7        prismagraphql/prisma:1.8   \"/bin/sh -c /app/sta…\"   2 hours ago         Restarting (1) Less than a second ago                                      two_hackernews_1\n```\n\n```text\nSQL_PASSWORD=myuniquepassword\nSQL_INTERNAL_PORT=3307\nSQL_CLIENT_PORT=3307\n```\n\n```text\nexpose:\n    - \"${SQL_INTERNAL_PORT}\"\n```\n\n```text\nversion: '3'\nservices:\nhackernews:\n    image: prismagraphql/prisma:1.8\n    restart: always\n    ports:\n    - \"${CLIENT_PORT}:${INTERNAL_PORT}\"\n    environment:\n    PRISMA_CONFIG: |\n        port: $INTERNAL_PORT\n        managementApiSecret: $PRISMA_MANAGEMENT_API_SECRET\n        databases:\n        default:\n            connector: mysql\n            host: mysql_first\n            port: 3306\n            user: root\n            password: $SQL_PASSWORD\n            migrations: true\n        second:\n            connector: mysql\n            host: mysql_second\n            port: 3306\n            user: root\n            password: $SQL_PASSWORD\n            migrations: true\nmysql_first:\n    image: mysql:5.7\n    restart: always\n    environment:\n    MYSQL_ROOT_PASSWORD: $SQL_PASSWORD\n    ports:\n     - 3307:3306\n    volumes:\n    - ./custom/:/etc/mysql/conf.d/my.cnf\n    - mysql:/var/lib/mysql\n\n mysql_second:\n    image: mysql:5.7\n    restart: always\n    environment:\n    ports:\n     - 3308:3306\n    MYSQL_ROOT_PASSWORD: $SQL_PASSWORD\n```\n\n```text\nSQL_INTERNAL_PORT\n```\n\n```text\n3307\n```\n\n```text\n3306\n```\n\n```text\nenvironment:\n  WORDPRESS_DB_HOST: db-wordpress\n```\n\n```text\ncontainer_name: db-wordpress\nenvironment:\n  VIRTUAL_PORT: 3307\nexpose:\n  - 3307\n```\n\n```text\nversion: '3.8'\n\nvolumes:\n  mysql_data:\n    driver: local\n\nservices:\n  mysql:\n    image: mysql:5.7\n    volumes:\n      - mysql_data:/var/lib/mysql\n    environment:\n      MYSQL_ROOT_PASSWORD: root\n      MYSQL_DATABASE: keycloak\n      MYSQL_USER: keycloak\n      MYSQL_PASSWORD: password\n      MYSQL_TCP_PORT: 3307\n    ports:\n    - 3307:3307\n    expose:\n      - 3307\n  keycloak:\n    image: quay.io/keycloak/keycloak:latest\n    environment:\n      DB_VENDOR: MYSQL\n      DB_ADDR: mysql\n      DB_DATABASE: keycloak\n      DB_USER: keycloak\n      DB_PASSWORD: password\n      DB_PORT: 3307\n      KEYCLOAK_USER: admin\n      KEYCLOAK_PASSWORD: Pa55w0rd\n      # Uncomment the line below if you want to specify JDBC parameters. The parameter below is just an example, and it shouldn't be used in production without knowledge. It is highly recommended that you read the MySQL JDBC driver documentation in order to use it.\n      #JDBC_PARAMS: \"connectTimeout=30000\"\n    ports:\n      - 8040:8080\n    depends_on:\n      - mysql\n```\n\n```text\nMYSQL_TCP_PORT\n```\n\n========================================\n\nComments:\n- Could you provide what errors do you have when starts app? and could you provide `docker-compose ps` output?\n- Under ports I get \"3306/tcp, 0.0.0.0:3307->3307/tcp\"\n- And the hackernews Prisma Service is not able to connect to the MySQL database on port 3307. I am going to add the errors above.\n- Prisma should use internal `3306` port. And you can expose another (3307) port to host machine. But i cant understand why prisma try to connect to `3307` port. According to config it should connect to `3306`\n- also you can remove ` expose: - \"${SQL_INTERNAL_PORT}\"` line. Mysql already exposed this port\n- I am telling Prisma to connect to port 3307. I added the .env above.\n- Note, another MySQL container is being run on port 3306 and is being used by another Prisma database service.\n- it is not a problem. Just name this container `my_second_mysql` and use this name as `hostname`\n- But you need to have different EXTERNAL ports for mysql servers\n- Thank you Bukharov! You are absolutely correct, the machine had ran out of memory and as a result I was assuming that I was doing something wrong (hence why I wanted to run the MySQL database on a different port than 3306).\n- Thanks Muhammed Ozdogan! I also only could change the port when I add MYSQL_TCP_PORT\n- hahahah, the fact that this was the exact problem... XD\n- thanks, `MYSQL_TCP_PORT= 3307` env along with `ports: - \"3307:3307\"` did it for me","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":382,"estimatedTokens":3491}}18{"id":"stack-68100340","source":"stackoverflow","questionId":68100340,"title":"How to create a prisma model from a SQL view","tags":["view","introspection","prisma"],"text":"Title: How to create a prisma model from a SQL view\nTags: view, introspection, prisma\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have 'prisma introspect' create models for views in Postgres ?\n\n========================================\n\nCode:\n```text\nschema.prisma\n```\n\n```text\nmodel\n```\n\n========================================\n\nComments:\n- Great, that's simple enough. Thankyou\n- Found this too : prisma.io/docs/guides/database/advanced-database-tasks/&hellip;\n- @Ryan can you describe how we add the model to the shema.prisma and how we generate the prisma client? I have create a view into the database, then i declare it as a model into prisma.schema and the i tried to generate the prisma client, with the command npx prisma generate. But i get the following error: The model with database name \"test_view\" could not be defined because another model with this name exists: \"test_view\"","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":24,"estimatedTokens":225}}19{"id":"stack-65474757","source":"stackoverflow","questionId":65474757,"title":"Nexus Prisma - How to handle createdAt and updatedAt with crud globally?","tags":["typescript","prisma","nexus-js"],"text":"Title: Nexus Prisma - How to handle createdAt and updatedAt with crud globally?\nTags: typescript, prisma, nexus-js\nSource: Stack Overflow\n\nQuestion:\nFirst thing I came up with, is by calling `computedInputs` in the `nexusPrisma` option. But it won't work since they need to be handled differently depending on the situation, but globally:\n\n```\n1. create -> createdAt = now, updatedAt = null\n2. update -> createdAt = keep as it is, updatedAt = now\n```\n\nIn order to make it work, I need to set computedInputs individually like so:\n\n```\nt.crud.createOneX({\n computedInputs: {\n createdAt: () => DateTime.utc().toString(),\n updatedAt: () => null,\n },\n});\n\nt.crud.updateOneX({\n computedInputs: {\n createdAt: () => undefined,\n updatedAt: () => DateTime.utc().toString(),\n },\n});\n```\n\nWhile this might work, I'm unable to \"compute\" these inputs on the nested models. In order to prevent passing createdAt/updatedAt, I have to create another `t.crud` on that resource as well, without these timestamps.\n\nThe last workaround for this that might work, is to not use `t.crud` at all, which is a bummer.\n\n========================================\n\nCode:\n```text\n1. create -> createdAt = now, updatedAt = null\n2. update -> createdAt = keep as it is, updatedAt = now\n```\n\n```js\nt.crud.createOneX({\n  computedInputs: {\n    createdAt: () => DateTime.utc().toString(),\n    updatedAt: () => null,\n  },\n});\n\nt.crud.updateOneX({\n  computedInputs: {\n    createdAt: () => undefined,\n    updatedAt: () => DateTime.utc().toString(),\n  },\n});\n```\n\n```text\ncomputedInputs\n```\n\n```text\nnexusPrisma\n```\n\n```text\nt.crud\n```\n\n```text\nt.crud\n```\n\n```text\nmodel Post {\n  id               Int                @id @default(autoincrement())\n  title            String\n  content          String?\n  published        Boolean?           @default(false)\n  createdAt        DateTime           @default(now())\n  updatedAt        DateTime           @updatedAt\n}\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\n@default(now())\n```\n\n```text\n@updatedAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\n@default(now())\n```\n\n```text\n@updatedAt\n```\n\n========================================\n\nComments:\n- I eventually ended up manually creating these fields. Felt more in control 😅. PS - If you have just signed up in order to answer my question, then I just want to let you know that you're a legend.\n- When using `@default(now())` and `@updatedAt` set 2 differents timestamp when created, determine if a record have been updated using `createdAt !== updatedAt` always returns `true`.\n- Be aware that subsequently adding `createdAt` with `@default(now())` adds the current date. This may lead to wrong intepretation of the creation date later down the line.\n- `default(now())` sends in same timestamp as `@updatedAt`. this is so messed up.","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":124,"estimatedTokens":702}}20{"id":"stack-68418224","source":"stackoverflow","questionId":68418224,"title":"Prisma $queryRaw with variable length parameter list","tags":["postgresql","prisma"],"text":"Title: Prisma $queryRaw with variable length parameter list\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using Prisma with Postgres. I need to use $queryRaw for a particular query due to use of unsupported tsvector type in the underlying table. In this query, I also need to use an 'in' statement where the items in the 'in' list need to be parameterised.. I have tried this\n\n```\nconst ids = [41, 55]\nconst result = await prisma.$queryRaw`select * from users where id in (${ids})`;\n```\n\nbut I get a kernel panic\n\n```\nPANIC in /root/.cargo/git/checkouts/rust-postgres-dc0fca9be721a90f/8a61d46/postgres-types/src/lib.rs:762:18\nexpected array type\n```\n\nI also tried this...\n\n```\nconst result = await prisma.$queryRaw`select * from users where id in (${ids.join(',')})`;\n```\n\nbut then I get this error...\n\n```\nRaw query failed. Code: `22P03`. Message: `db error: ERROR: incorrect binary data format in bind parameter 1`\n```\n\nThe sql-template-tag library which I think is used by prisma, has a way of supporting this so after installing and importing it, I tried this..\n\n```\nconst result = await prisma.$queryRaw`select * from users where id in (${join(ids)})`;\n```\n\nbut this throws the same error.\n\nany Idea how I can achieve this?\n\n========================================\n\nTop Answer:\nAs @MichaelDausmann has mentioned above, there is a Prisma function that joins array items and formats the SQL by the types of parameters. But when you use uuid type, Prisma's join function formats the parameters adding double apostrophe. So you can take error like 'type mismatch' in PostreSQL. Alternatively, you can use native Array.join function to build a sql string and send it to Prisma raw query function using Prisma.raw function.\n\n```\nconst sql = `select * from table where id in (${idArray.map(v => `'${v}'::uuid`).join(\",\")})`\nresult = await prisma.$queryRaw(Prisma.raw(sql))\n```\n\n========================================\n\nCode:\n```text\nconst ids = [41, 55]\nconst result = await prisma.$queryRaw`select * from users where id in (${ids})`;\n```\n\n```text\nPANIC in /root/.cargo/git/checkouts/rust-postgres-dc0fca9be721a90f/8a61d46/postgres-types/src/lib.rs:762:18\nexpected array type\n```\n\n```text\nconst result = await prisma.$queryRaw`select * from users where id in (${ids.join(',')})`;\n```\n\n```text\nRaw query failed. Code: `22P03`. Message: `db error: ERROR: incorrect binary data format in bind parameter 1`\n```\n\n```text\nconst result = await prisma.$queryRaw`select * from users where id in (${join(ids)})`;\n```\n\n```text\nimport { Prisma } from \"@prisma/client\";\n\nconst ids = [1, 3, 5, 10, 20];\nconst result = await prisma.$queryRaw`SELECT * FROM User WHERE id IN (${Prisma.join(\n  ids\n)})`;\n```\n\n```text\nconst sql = `select * from table where id in (${idArray.map(v => `'${v}'::uuid`).join(\",\")})`\nresult = await prisma.$queryRaw(Prisma.raw(sql))\n```\n\n========================================\n\nComments:\n- I flagged this until I realized you were answering your own question. But thank you for finding it, because Prisma's docs can be dense and not conducive to finding what you are looking for.\n- You just switched from tag templates to `Prisma.raw` which means the values are not sanitized anymore and that can open you up for SQL injection.\n- How do I mitigate the risk?","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":96,"estimatedTokens":822}}21{"id":"stack-65950407","source":"stackoverflow","questionId":65950407,"title":"Prisma many-to-many relations: create and connect","tags":["typescript","graphql","prisma","prisma-graphql","prisma2"],"text":"Title: Prisma many-to-many relations: create and connect\nTags: typescript, graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nIn my Prisma schema, I have a many-to-many relationship between posts and categories. I've added `@map` options to match the Postgres snake_case naming convention:\n\n```\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n body String?\n categories PostCategory[]\n\n @@map(\"post\")\n}\n\nmodel Category {\n id Int @id @default(autoincrement())\n name String\n posts PostCategory[]\n\n @@map(\"category\")\n}\n\nmodel PostCategory {\n categoryId Int @map(\"category_id\")\n postId Int @map(\"post_id\")\n category Category @relation(fields: [categoryId], references: [id])\n post Post @relation(fields: [postId], references: [id])\n\n @@id([categoryId, postId])\n @@map(\"post_category\")\n}\n```\n\nI'm trying to create a post with multiple categories at the same time. If a category exists, I'd like to `connect` the category to the post. If the category doesn't exist, I'd like to create it. The creation part is working well, but the connection part is problematic:\n\n```\nawait prisma.post.create({\n data: {\n title: 'Hello',\n categories: {\n create: [{ category: { create: { name: 'News' } } }],\n connect: {\n categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId\n },\n },\n },\n });\n```\n\nHow can I connect an existing category to a new post with the schema that I have?\n\n========================================\n\nTop Answer:\nAfter hours of trying I finally came up with the following solution for my use case.\n\n```\npark[] exercise[]\n```\n\n```\n// create parks\nconst parks = await prisma.park.createMany({data: [...]});\n\n// create and connect exercises\nconst exercises = [...];\nawait Promise.all(\n exercises.map(async (exercise) => {\n await prisma.exercise.create({\n data: {\n ...exercise,\n parks: {\n connect: parks.map((park) => ({ id: park.id })),\n },\n },\n });\n }),\n);\n```\n\n========================================\n\nCode:\n```text\nmodel Post {\n  id         Int            @id @default(autoincrement())\n  title      String\n  body       String?\n  categories PostCategory[]\n\n  @@map(\"post\")\n}\n\nmodel Category {\n  id    Int            @id @default(autoincrement())\n  name  String\n  posts PostCategory[]\n\n  @@map(\"category\")\n}\n\nmodel PostCategory {\n  categoryId Int      @map(\"category_id\")\n  postId     Int      @map(\"post_id\")\n  category   Category @relation(fields: [categoryId], references: [id])\n  post       Post     @relation(fields: [postId], references: [id])\n\n  @@id([categoryId, postId])\n  @@map(\"post_category\")\n}\n```\n\n```text\nawait prisma.post.create({\n    data: {\n      title: 'Hello',\n      categories: {\n        create: [{ category: { create: { name: 'News' } } }],\n        connect: {\n          categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId\n        },\n      },\n    },\n  });\n```\n\n```text\n@map\n```\n\n```text\nconnect\n```\n\n```text\nawait prisma.post.create({\n        data: {\n          title: 'Hello',\n          categories: {\n            create: [\n              {\n                category: {\n                  create: {\n                    name: 'category-1',\n                  },\n                },\n              },\n              { category: { connect: { id: 10 } } },\n            ],\n          },\n        },\n      });\n```\n\n```text\nconnectOrCreate\n```\n\n```text\nawait Promise.all(DEFAULT_FILES[2].map(file => prisma.file.create({\n    data: {\n      ...file,\n      user_id: userId,\n      parent_id: homeFolder.id,\n      tags: {\n        create: file.tags?.map(name => ({\n          tag: {\n            connect: {\n              id: tags.find(t => t.name === name)?.id\n            }\n          }\n        }))\n      },\n    }\n  })))\n```\n\n```text\nawait prisma.postCategory.create({\n  data: {\n    category: {\n      connectOrCreate: {\n        id: categoryId\n      }\n    },\n    posts: {\n      create: [\n        {\n          title: 'g3xxxxxxx',\n          body: 'body g3xxxxx'\n        }\n      ],\n    },\n  },\n})\n```\n\n```js\nlet args =[1,2,3,4]\ntags: {\n      create: args.tags?.map(tagId=>({\n          tag:{\n              connect:{\n                  id:tagId\n              }\n          }\n      }))\n    },\n }\n```\n\n```text\npark[] <-> exercise[]\n```\n\n```text\n// create parks\nconst parks = await prisma.park.createMany({data: [...]});\n\n// create and connect exercises\nconst exercises = [...];\nawait Promise.all(\n  exercises.map(async (exercise) => {\n    await prisma.exercise.create({\n      data: <any>{\n        ...exercise,\n        parks: {\n          connect: parks.map((park) => ({ id: park.id })),\n        },\n      },\n    });\n  }),\n);\n```\n\n========================================\n\nComments:\n- This exhibits strange behavior. If the `{ categoryId: 1, postId: 1 }` bridge record exists in the `post_category` table, then it replaces the bridge record with `{ categoryId: 1, postId: new_id }`. In other words, it re-assigns another post's category to this new post. I don't want any other post to be impacted when I create a new post. I'd like to create a new category if the category doesn't exist, or add a new bridge record if it does. There's a good example using `create` and `set` on implicit relations here: (url to ), but it doesn't work b/c I'm using explicit relation.\n- Here's the URL that I was referring to in my previous comment: prisma.io/docs/support/help-articles/&hellip; The example there uses `tags: { set: [{ id: 1 }, { id: 2 }], create: { name: 'typescript' } }`, which is what I'd like to do, but can't seem to get it to work with my explicit relationship.\n- Based on the docs you linked to, I think I want something like this, but this throws an exception because I can't link from `categoryId_postId` to `category` (sorry about the formatting): `connectOrCreate: { create: { category: { create: { name: 'category-1' } }, }, where: { categoryId_postId: { category: { name: 'category-1' }, }, }`\n- In that case, this should work: `await prisma.post.create({ data: { title: 'title', categories: { create: { category: { connect: { id: 1 } } } }, }, })` This should connect the post to an existing category and will create the relation in the join table as well.\n- Could you tell me the type of file in your solution? I got it to work, but don't know the type of the input. I thought it's Prisma.FileCreateInput but tags has no map property.\n- It's a `seed.ts` that I execute with `\"seed\": \"ts-node .&#47;prisma&#47;seed.ts\"`\n- Nice one! This is what I needed, although I opted for a little different expression: connect: parks.map(({ id }) => ({ id })),","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":248,"estimatedTokens":1642}}22{"id":"stack-64535044","source":"stackoverflow","questionId":64535044,"title":"Timestamp with timezone column in Prisma","tags":["prisma"],"text":"Title: Timestamp with timezone column in Prisma\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI am evaluating Prisma and I am a complete noob...\n\n- I am using Postgresql\n\n- I have the following model definition\n\n```\nmodel Sth {\n id Int @default(autoincrement()) @id\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n expiresAt DateTime?\n}\n```\n\nThe `createdAt` column translates to\n\n`createdAt | timestamp(3) without time zone | | not null | CURRENT_TIMESTAMP`\n\nSince I am planing to really work with the timestamps - I need them to be `timestamp with time zone`.\n\nHow can I achieve this with Prisma?\n\n**Edit NOW() > '2021-02-16'**: Prisma now, has the \"native types\"\n\n- https://github.com/prisma/prisma/releases/tag/2.17.0\n\n- https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#postgresql-6\n\n========================================\n\nTop Answer:\nCurrently the `timestamptz` field is not supported as Prisma automatically converts the Timestamp you sent to UTC. The support will be available in a further version of Prisma via this request.\n\nAs a workaround, you would need to convert the timestamp to a specific required timezone as Prisma would save it in UTC in the DB.\n\n========================================\n\nCode:\n```text\nmodel Sth {\n  id                 Int       @default(autoincrement()) @id\n  createdAt          DateTime  @default(now())\n  updatedAt          DateTime  @updatedAt\n  expiresAt          DateTime?\n}\n```\n\n```text\ncreatedAt\n```\n\n```text\ncreatedAt          | timestamp(3) without time zone |              | not null      | CURRENT_TIMESTAMP\n```\n\n```text\ntimestamp with time zone\n```\n\n```text\nmodel Sth {\n  id                 Int       @default(autoincrement()) @id\n  createdAt          DateTime  @default(now()) @db.Timestamptz(3)\n  updatedAt          DateTime  @updatedAt @db.Timestamptz(3)\n  expiresAt          DateTime? @db.Timestamptz(3)\n}\n```\n\n```text\n'UTC'\n```\n\n```text\n@default\n```\n\n```text\ntimestamptz\n```\n\n========================================\n\nComments:\n- Thanks. I think you meant to link this? github.com/prisma/prisma/issues/3447 ? Anyway - this helped!\n- Yeah that's the main request.\n- Pls help update this answer, thanks\n- What does the (3) mean? The documentation doesn't seem to say either, just calls it `x`. According to ChatGPT it means precision and ranges from 0 to 6, with 3 being milliseconds and 6 being microseconds. PostgreSQL defaults to 6. Can one omit the precision in Prisma?\n- @Eloff it is related to precision of millisecond rounding. I haven’t done any experimentation in this, but my assumption is that if one omits it, and the version of postgresql defaults to 6, then they would see a time stamp with time zone with 6 decimal places. From past experience, Prisma doesn’t mess with database defaults unless the documentation says. Please your experience!\n- When I add the `Timestamptz` attribute, it seems that Prisma is still converting the ISO8601 date with offset to UTC.\n- bug - github.com/prisma/prisma/issues/7915","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":96,"estimatedTokens":756}}23{"id":"stack-55830930","source":"stackoverflow","questionId":55830930,"title":"Ordering by multiple columns in Prisma","tags":["prisma","prisma-graphql"],"text":"Title: Ordering by multiple columns in Prisma\nTags: prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI know currently **Prisma** doesn't support ordering by multiple scalars fields, (see this issue: https://github.com/prisma/prisma/issues/62).\nBut, I'm wondering if there is someone who found a solution to work around this issue without using executeRaw mutation (raw **SQL**) because I have many places in my code where I need to order by multiple fields and I don't want to use executeRaw in so many places.\nI will appreciate any suggestions. Thank you!\n\n========================================\n\nTop Answer:\nI don't think there's a solution, In my project, I need random order, increment/decrement, aggregation... use raw finally.\n\n========================================\n\nCode:\n```text\nconst users = await prisma.user.findMany({\n   select: {\n      email: true,\n      role: true,\n   },\n   orderBy: [\n      {\n         email: 'desc',\n      },\n      {\n         role: 'desc',\n      }\n   ],\n})\n```\n\n========================================\n\nComments:\n- Ok, but how do I write `... ORDER BY (foo = 1) DESC, bar ASC, foo ASC, baz ASC;`?\n- What do you mean by (foo = 1) ?\n- I want rows where foo equals to 1 be sorted before the rest. In SQL you can do that as I've written it.","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":40,"estimatedTokens":321}}24{"id":"stack-63315725","source":"stackoverflow","questionId":63315725,"title":"'.' is not recognized as an internal or external command thrown when used in exec(), but not when run from command line","tags":["javascript","node.js","windows","npm","prisma"],"text":"Title: '.' is not recognized as an internal or external command thrown when used in exec(), but not when run from command line\nTags: javascript, node.js, windows, npm, prisma\nSource: Stack Overflow\n\nQuestion:\nThe following is part of a script that is run using npm run test.\n\n```\nasync setup() {\n process.env.DATABASE_URL = this.databaseUrl;\n this.global.process.env.DATABASE_URL = this.databaseUrl;\n await exec(`./node_modules/.bin/prisma migrate up --create-db --experimental`);\n return super.setup();}\n```\n\nThis throws the following error\n\n```\nCommand failed: ./node_modules/.bin/prisma migrate up --create-db --experimental\n'.' is not recognized as an internal or external command,\noperable program or batch file.\n```\n\nWhen run from the cmd the command works as expected. What is the correct way to reference the binary file within exec()? I am using windows incase that is relevant.\n\n========================================\n\nCode:\n```text\nasync setup() {\n    process.env.DATABASE_URL = this.databaseUrl;\n    this.global.process.env.DATABASE_URL = this.databaseUrl;\n    await exec(`./node_modules/.bin/prisma migrate up --create-db --experimental`);\n    return super.setup();}\n```\n\n```text\nCommand failed: ./node_modules/.bin/prisma migrate up --create-db --experimental\n'.' is not recognized as an internal or external command,\noperable program or batch file.\n```\n\n```text\nconst path = require(\"path\");\nconst prismaBinary = \"./node_modules/.bin/prisma\";\nawait exec(\n  `${path.resolve(prismaBinary)} migrate up --create-db --experimental`\n);\n```\n\n========================================\n\nComments:\n- My guess is that `npm run test` is running in a different shell than the command line (probably Windows CMD shell) on which you're trying (and failing) to execute the command directly. That command looks like it's designed to run in bash or similar.\n- You really can run `.&#47;node_modules&#47;...` from the CMD commandline? I doubt that. Or do you change into the respective subdirectory. You could use `path.resolve()` to resolve the relative path to your executable into an absolute path. On windows systems, `path.resolve()` can also deal with linux path delimeters `&#47;` and will return a path with windows path delimeters `\\`\n- If you have some bash compatible shell installed (for instance MINGW64 which is installed with git for windows) you could also set your script-shell for npm like shown in this question stackoverflow.com/questions/23243353/&hellip;\n- @derpirscher you are correct i had a terminal open within the root of the project. And your solution worked. Thank you.\n- You should enclose your resolved path in double quotes, as it may contain whitespaces","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":58,"estimatedTokens":671}}25{"id":"stack-75905276","source":"stackoverflow","questionId":75905276,"title":"Using Prisma Client with Supabase Edge Functions","tags":["javascript","npm","prisma","deno","supabase"],"text":"Title: Using Prisma Client with Supabase Edge Functions\nTags: javascript, npm, prisma, deno, supabase\nSource: Stack Overflow\n\nQuestion:\nI am trying to use the generated `@prisma/client` together with Supabase Edge functions. When running `npx prisma generate` the default location would be in my `node_modules` folder, which is a problem since I can't access it when using edge functions. I therefore added the `output` property to my `prisma.schema` file and the client gets generated in the correct location. My `schema.prisma` looks like this:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./../supabase/functions/_shared/prisma-client\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = \"...\"\n directUrl = \"...\"\n}\n\nmodel Users {}\n```\n\nI tried importing the client in multiple ways into my edge functions:\n\n```\n// Attempt #1 (according to: https://deno.land/manual@v1.14.2/npm_nodejs/std_node#loading-commonjs-modules):\nimport { createRequire } from 'https://deno.land/std@0.155.0/node/module.ts'\nconst require = createRequire(import.meta.url)\nconst cjsModule = require('../_shared/prisma-client')\n/* Error: worker thread panicked TypeError: Cannot read properties of undefined (reading 'timeOrigin')\n at https://deno.land/std@0.155.0/node/perf_hooks.ts */\n/* Note: I also tried different versions of the std library */\n\n// Attempt #2:\nimport { PrismaClient } from '../_shared/prisma-client'\n/* Error: Unable to load a local module: \"file:///C:/Users/.../supabase/functions/_shared/prisma-client\".\n Please check the file path. */\n\n// Attempt #3:\nimport { serve } from 'server'\nimport { PrismaClient } from '../_shared/prisma-client/index.d.ts'\n\nserve((_req: Request) => {\n const prisma = new PrismaClient()\n})\n/* Error: worker thread panicked Uncaught SyntaxError: Missing initializer in const declaration\n at file:///home/deno/functions/_shared/prisma-client/index.d.ts:53:11 */\n```\n\nI furthermore tried to convert the module from CommonJS into an ESM module using the `cjs-to-es6` npm package. But this also didn't work.\n\nSo my question is: Why my attempts failed, and (perhaps more importantly) how do I get it to work?\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  output          = \"./../supabase/functions/_shared/prisma-client\"\n}\n\ndatasource db {\n  provider  = \"postgresql\"\n  url       = \"...\"\n  directUrl = \"...\"\n}\n\nmodel Users {}\n```\n\n```js\n// Attempt #1 (according to: https://deno.land/manual@v1.14.2/npm_nodejs/std_node#loading-commonjs-modules):\nimport { createRequire } from 'https://deno.land/std@0.155.0/node/module.ts'\nconst require = createRequire(import.meta.url)\nconst cjsModule = require('../_shared/prisma-client')\n/* Error: worker thread panicked TypeError: Cannot read properties of undefined (reading 'timeOrigin')\n    at https://deno.land/std@0.155.0/node/perf_hooks.ts */\n/* Note: I also tried different versions of the std library */\n\n// Attempt #2:\nimport { PrismaClient } from '../_shared/prisma-client'\n/* Error: Unable to load a local module: \"file:///C:/Users/.../supabase/functions/_shared/prisma-client\".\n  Please check the file path. */\n\n// Attempt #3:\nimport { serve } from 'server'\nimport { PrismaClient } from '../_shared/prisma-client/index.d.ts'\n\nserve((_req: Request) => {\n    const prisma = new PrismaClient()\n})\n/* Error: worker thread panicked Uncaught SyntaxError: Missing initializer in const declaration\n    at file:///home/deno/functions/_shared/prisma-client/index.d.ts:53:11 */\n```\n\n```text\n@prisma/client\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnode_modules\n```\n\n```text\noutput\n```\n\n```text\nprisma.schema\n```\n\n```text\nschema.prisma\n```\n\n```text\ncjs-to-es6\n```\n\n```js\nimport { Prisma, PrismaClient } from \"../generated/client/deno/edge.ts\";\nimport { config } from \"https://deno.land/std@0.163.0/dotenv/mod.ts\";\n\nconst envVars = await config();\n\nconst prisma = new PrismaClient({\n  datasources: {\n    db: {\n      url: envVars.DATABASE_URL,\n    },\n  },\n});\n```\n\n```text\nsupabase-js\n```\n\n========================================\n\nComments:\n- I came to the conclusion that supabase-js would be the better choice in this case. However, it lacks typescript support for my database models, which was the reason to use prisma in the first place.\n- You can generate types for supabase-js from your Database using the CLI: supabase.com/docs/guides/api/rest/generating-types\n- I was just about to say I need to thank whomever took the time to self-answer this and lo and behold we've worked together. Thanks Thor!","metadata":{"transformedAt":"2026-08-18T18:33:14.814Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":149,"estimatedTokens":1139}}26{"id":"stack-53683009","source":"stackoverflow","questionId":53683009,"title":"Row level security using prisma and postgres","tags":["postgresql","graphql","prisma","row-level-security","prisma-graphql"],"text":"Title: Row level security using prisma and postgres\nTags: postgresql, graphql, prisma, row-level-security, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am using prisma and yoga graphql servers with a postgres DB.\n\nI want to implement authorization for my graphql queries. I saw solutions like graphql-shield that solve `column level security` nicely - meaning I can define a permission and according to it block or allow a specific table or column of data (on in graphql terms, block a whole entity or a specific field).\n\nThe part I am stuck on is `row level security` - filtering rows by the data they contain - say I want to allow a logged in user to view only the data that is related to him, so depending on the value in a user_id column I would allow or block access to that row (the logged in user is one example, but there are other usecases in this genre).\n\nThis type of security requires running a query to check which rows the current user has access to and I can't find a way (that is not horrible) to implement this with prisma.\n\nIf I was working without prisma, I would implement this in the level of each resolver but since I am forwarding my queries to prisma I do not control the internal resolvers on a nested query.\n\nBut I do want to work with prisma, so one idea we had was handling this in the DB level using postgres policy. This could work as follows:\n\n- Every query we run will be surrounded with “begin transaction” and “commit transaction”\n\n- Before the query I want to run “set local context.user_id to 5\"\n\n- Then I want to run the query (and the policy will filter results according to the current_setting(‘context.user_id’))\n\nFor this to work I would need prisma to allow me to either add pre/post queries to each query that runs or let me set a context for the db.\n\nBut these options are not available in prisma.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nWith the approach you're looking to take, I'd definitely recommend a look at Graphile. It approaches row-level security essentially the same way that you're thinking of. Unfortunately, it seems like Prisma doesn't help you move away from writing traditional REST-style controller methods in this regard.\n\n========================================\n\nCode:\n```text\ncolumn level security\n```\n\n```text\nrow level security\n```\n\n```text\nprisma-client\n```\n\n```text\nprisma-binding\n```\n\n```text\nprisma-binding\n```\n\n```text\nprisma-client\n```\n\n```text\nprisma-client\n```\n\n========================================\n\nComments:\n- Without the schema, I can't give a definitive answer but have you tried to create a policy using ((id)::name = SESSION_USER) or something in those lines. SESSION_USER is the role used to connect to the DB.\n- I assume you are using `prisma-binding` for the forwarding. Maybe using `prisma-client` would be a better choice so you would implement this logic inside resolvers ? (That would also work with nested queries)\n- Regarding session user my connection to the db through prisma is always with the same user and role. The users are managed in the applicatuon level, not the db. I dont think it is even possible to have a specific role per query to prisma. If that was possible it could solve the problem. Is it possible and i am missing something?","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":819}}27{"id":"stack-54416406","source":"stackoverflow","questionId":54416406,"title":"Add data from a JSON file to the Prisma database with a seed file","tags":["graphql","prisma"],"text":"Title: Add data from a JSON file to the Prisma database with a seed file\nTags: graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to seed my database with some data from a JSON file\n\n```\n//continent-data.json\n[\n {\n \"continent\": \"far east\",\n \"imageURL\": \"#\"\n },\n {\n \"continent\": \"ASIA\",\n \"imageURL\": \"#\"\n },\n]\n```\n\nHere is my seed.js file\n\n```\n//seed.js\nconst dotenv = require('dotenv');\nconst { Prisma } = require('./src/generated/prisma-client');\nconst continentData = require('./continent-data.json');\n\ndotenv.config();\n\nconst db = new Prisma({\n secret: process.env.PRISMA_SECRET,\n endpoint: process.env.PRISMA_ENDPOINT\n});\n\nconst seedContinents = () => {\n // adding continents to the data\n Promise.all(\n continentData.map(async continentItem => {\n const { imageURL, continent } = continentItem;\n const response = await db.createContinent({\n data: {\n name: continent || 'default name',\n imageURL,\n }\n });\n return response;\n })\n );\n};\n\nseedContinents();\n```\n\nWhen I run `node seed.js`\n\nIt fails and it throws the following error\n\nUnhandledPromiseRejectionWarning: Error: Variable '$data' expected value of type 'ContinentCreateInput!' but got: {\"data\":{\"name\":\"far east\",\"imageURL\":\"#\",\"destinations\":[]}}. Reason: 'name' Expected non-null value, found null.\n\nI believe I am passing correct data there in the correct format. but It says name field got a null value. but the error message itself says that name field has got a string value \"far east\"\n\nI have provided necessary portions of the Prisma schema as well.\n\nhttps://i.sstatic.net/La25j.png\n\n========================================\n\nTop Answer:\nYou can think of Prisma object (Prisma client) which you have imported at the top as a helper class. After your instantiate it you then have access to the javascript functions which mostly mirror the Prisma Server CRUD functions which have been generated for you based on your `datamodel.graphql` file.\n\nIf you look at the example docs on the Prisma client page you can see that there are two ways to pass data to get the same result. On the one hand you can invoke the javascript function:\n\n```\ndb.createContinent({\n name: continent || 'default name',\n imageURL,\n });\n```\n\nAnd on the other hand, you can directly run a GraphQL query on the Prisma endpoint, \n\n```\nmutation {\n createContinent(data: {\n name: continent || 'default name',\n imageURL\n }) {\n name\n continent\n }\n}\n```\n\nThe second way you can do in the GraphQL playground and is directly interacting with the data. The first example which uses the Prisma client auto generated javascript functions is a wrapper and only requires the input data without the data: object wrapper. So without the \n\n`data: { { ContinentCreateInput object shape }}` \n\nThe docs don't really cover it in detail, and it took me a while to also wonder why it wouldn't fit the shape you have specified in your GraphQL types.\n\nThe first way is the recommended way to abstract away and protect your application layer from the raw database CRUD methods. See `Prisma client`\n\n========================================\n\nCode:\n```text\n//continent-data.json\n[\n  {\n    \"continent\": \"far east\",\n    \"imageURL\": \"#\"\n  },\n  {\n    \"continent\": \"ASIA\",\n    \"imageURL\": \"#\"\n  },\n]\n```\n\n```text\n//seed.js\nconst dotenv = require('dotenv');\nconst { Prisma } = require('./src/generated/prisma-client');\nconst continentData = require('./continent-data.json');\n\ndotenv.config();\n\nconst db = new Prisma({\n  secret: process.env.PRISMA_SECRET,\n  endpoint: process.env.PRISMA_ENDPOINT\n});\n\nconst seedContinents = () => {\n  // adding continents to the data\n  Promise.all(\n    continentData.map(async continentItem => {\n      const { imageURL, continent } = continentItem;\n      const response = await db.createContinent({\n        data: {\n          name: continent || 'default name',\n          imageURL,\n        }\n      });\n      return response;\n    })\n  );\n};\n\nseedContinents();\n```\n\n```text\nnode seed.js\n```\n\n```text\nconst response = await db.createContinent({\n          name: continent || 'default name',\n          imageURL,\n      });\n```\n\n```text\ndb.createContinent({\n      name: continent || 'default name',\n      imageURL,\n  });\n```\n\n```text\nmutation {\n  createContinent(data: {\n    name: continent || 'default name',\n    imageURL\n  }) {\n    name\n    continent\n  }\n}\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\ndata: { { ContinentCreateInput object shape }}\n```\n\n```text\nPrisma client\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":193,"estimatedTokens":1103}}28{"id":"stack-71916267","source":"stackoverflow","questionId":71916267,"title":"Prisma One-to-one relation issue","tags":["prisma"],"text":"Title: Prisma One-to-one relation issue\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI have just recently started using prisma and I ran into an issue with relations. I have a user model and an address model.\n\n```\nmodel User {\n id Int @id @unique @default(autoincrement())\n username String\n}\n\nmodel Address {\n id Int @id @unique @default(autoincrement())\n street String\n}\n```\n\nI need to add 2 addresses to the user: invoicing address and delivery address. In the address I don't need a user reference.\n\nI thought this would work without issues by adding this to the user model:\n\n```\ninvoiceAddress Address? @relation(name: \"iAddress\", fields: [iAddressId], references: [id])\n deliveryAddress Address? @relation(name: \"dAddress\", fields: [dAddressId], references: [id])\n iAddressId Int?\n dAddressId Int?\n```\n\nBut when saving the schema two user fields are added to the address model... which I don't need and now I have issues because they reference the same user model so I have to also name them and add scalar field...\n\nAm I missing something??? This should be a basic use case imo.\n\n========================================\n\nCode:\n```text\nmodel User {\n    id         Int      @id @unique @default(autoincrement())\n    username   String\n}\n\nmodel Address {\n    id         Int      @id @unique @default(autoincrement())\n    street     String\n}\n```\n\n```text\ninvoiceAddress   Address? @relation(name: \"iAddress\", fields: [iAddressId], references: [id])\n  deliveryAddress   Address? @relation(name: \"dAddress\", fields: [dAddressId], references: [id])\n  iAddressId Int?\n  dAddressId Int?\n```\n\n```text\nmodel User {\n  id              Int      @id @unique @default(autoincrement())\n  username        String\n  invoiceAddress  Address? @relation(name: \"iAddress\", fields: [iAddressId], references: [id])\n  deliveryAddress Address? @relation(name: \"dAddress\", fields: [dAddressId], references: [id])\n  iAddressId      Int?\n  dAddressId      Int?\n}\n\nmodel Address {\n  id           Int    @id @unique @default(autoincrement())\n  street       String\n  UserInvoice  User[] @relation(name: \"iAddress\")\n  UserDelivery User[] @relation(name: \"dAddress\")\n}\n```\n\n```text\nUserInvoice\n```\n\n```text\nUserDelivery\n```\n\n```text\ninvoiceAddress\n```\n\n```text\ndeliveryAddress\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":89,"estimatedTokens":563}}29{"id":"stack-73943274","source":"stackoverflow","questionId":73943274,"title":"Prisma findUnique is SQL injection safe?","tags":["stripe-payments","prisma"],"text":"Title: Prisma findUnique is SQL injection safe?\nTags: stripe-payments, prisma\nSource: Stack Overflow\n\nQuestion:\nI've created a Nuxt3 project whereby I am loading products from Stripe into a product shelf, it pulls all the basic information like the name, and the price, and description, but I have also pulled the product ID across.\n\nOn checkout I am getting stripe to create a new checkout session, before the session starts I'm validating by comparing store product ID's against the ids that have been brought in by the client.\n\n```\nexport async function validateProducts(client_cart) {\n var valid = false;\n\n for (let index = 0; index getProduct() will take the id and use findUnique() from prisma function to pull the data into the server to validate/check for stock/hold.\n\n```\nexport async function getProduct (id: string) {\n return await prisma.product.findUnique({\n where: {\n id: id,\n },\n })\n }\n```\n\nThis basically pulls directly from the client the cart product object, the id is then passed into the where clause of the findUnique() functionality. Would this be vulnerable to SQL injection or does Prisma 'cover' (for lack of a better term) those vulnerabilities?\n\nLooking through the prisma documentation:\n\n\"ORMs help reduce the amount of code. They save you from writing repetitive SQL statements for common CRUD (Create Read Update Delete) operations and escaping user input to prevent vulnerabilities such as SQL injections.\"\n\nRegardless, my two questions are:\n\n- It is bad to expose the productID from stripe to the client?\n\n- Would the prisma function of \"findUnique()\" be vulnerable to SQL injection?\n\n========================================\n\nTop Answer:\nI can help with the first question.\n\nThe product ID is just a unique identifier that Stripe generates for a product resource. As long as you keep your secret key safe, no one is able to retrieve the content of the product by just having the product ID.\n\n========================================\n\nCode:\n```text\nexport async function validateProducts(client_cart) {\n   var valid = false;\n\n   for (let index = 0; index < client_cart.length; index++) {\n    // needs validation\n        if (typeof(client_cart[index].id) != \"string\") {\n            break;\n        }\n\n        //getProduct  - uses findUnique\n        const product = await getProduct(client_cart[index].id);\n        console.log(product)\n\n        ... further validation occurs here that sets valid to true if it gets through all the \n             tests without breaking the loop\n   return valid;\n}\n```\n\n```text\nexport async function getProduct (id: string) {\n    return await prisma.product.findUnique({\n      where: {\n        id: id,\n      },\n    })\n  }\n```\n\n```text\n$queryRawUnsafe\n```\n\n```text\n$executeRawUnsafe\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":84,"estimatedTokens":687}}30{"id":"stack-68363120","source":"stackoverflow","questionId":68363120,"title":"PrismaJS Reverse Engineered from DB (like Hibernate)?","tags":["prisma"],"text":"Title: PrismaJS Reverse Engineered from DB (like Hibernate)?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI have a lot of experience using Hibernate to reverse engineer entity classes (Java) from the DB instance, (this process is the 'reverse' of evolving the DB based on writing entity classes). Often, with existing data and processes, it is essential to treat the DB as the single 'source of truth' and create entities based on the DB.\n\nI'm interested in using Prisma (TS/JS), and I've been looking for generators which can generate Prisma schema (which is used to generate entity classes) based on an existing DB (reverse engineering).\n\nIs there a way to reverse engineer the Prisma schema from an existing DB? Are there any known projects to add this functionality?\n\n========================================\n\nCode:\n```text\nprisma cli\n```\n\n```text\nnpx prisma introspect\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":21,"estimatedTokens":220}}31{"id":"stack-78460324","source":"stackoverflow","questionId":78460324,"title":"Could not figure out an ID in prisma.user.create() | Invalid Invocation | Prisma + Bunjs","tags":["postgresql","prisma","prisma2","bun"],"text":"Title: Could not figure out an ID in prisma.user.create() | Invalid Invocation | Prisma + Bunjs\nTags: postgresql, prisma, prisma2, bun\nSource: Stack Overflow\n\nQuestion:\nI'm using BunJS and Prisma for my personal project and testing via cucumberjs and keploy. The following are my version:-\n\nName\nVersion\n\nNode\nv21.6.0\n\nOS\nlinux-arm64-openssl-3.0.x\n\nPrisma Client\n5.12.1\n\nQuery Engine\n473ed3124229e22d881cb7addf559799debae1ab\n\nDatabase\npostgresql\n\nthis is my prisma schema:-\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\n// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?\n// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n name String?\n password String\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n \n posts Post[]\n \n comments Comment[]\n...\n}\n```\n\nWhen i am running the application without any testing part integrated, it is working fine. But while testing, only in Post calls, i'm getting error\n\n```\nInvalid `prisma.user.create()` invocation:Could not figure out an ID in create. This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic.\n```\n\nHere's my repo:- https://github.com/darkin424/Blog-Website .\n\nTo reproduce please the steps below:-\n\n```\n1. start the database docker instance\n2. install `keploy` with :- https://keploy.io/docs/server/installation/\n3. keploy record -c \"bun --watch index.ts\"\n4. make few post api call for creation like `signup`, `create-post`\n5. stop the docker instance\n6. keploy test -c \"bun --watch index.ts\"\n```\n\nWith this you can replicate the issue\n\nI tried looking at similar problems other faced and tried running:-\n\n```\nbunx prisma format\nbunx prisma validate\nbunx prisma migrate dev\nbunx prisma generate\n```\n\nif i consider post call's as noise my test works fine, but i want to test those POST calls as well.\n\n### Edit\n\nSo i updated the version of prisma to latest and now able to see the error better. In test mode, i'm getting the backtrace between my logs :-\n\n```\nthread 'tokio-runtime-worker' panicked at query-engine/connectors/sql-query-connector/src/database/operations/write.rs:194:22:\nCould not figure out an ID in create\nstack backtrace:\n 0: 0xffff62e79450 - \n 1: 0xffff627db750 - \n 2: 0xffff62e5afb4 - \n 3: 0xffff62e7cfc4 - \n 4: 0xffff62e7c968 - \n```\n\n========================================\n\nCode:\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\n// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?\n// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel User {\n  id        Int      @id @default(autoincrement())\n  email     String   @unique\n  name      String?\n  password  String\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n \n  posts  Post[]\n  \n  comments  Comment[]\n...\n}\n```\n\n```text\nInvalid `prisma.user.create()` invocation:Could not figure out an ID in create. This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic.\n```\n\n```text\n1. start the database docker instance\n2. install `keploy` with :- https://keploy.io/docs/server/installation/\n3. keploy record -c \"bun --watch index.ts\"\n4. make few post api call for creation like `signup`, `create-post`\n5. stop the docker instance\n6. keploy test -c \"bun --watch index.ts\"\n```\n\n```text\nbunx prisma format\nbunx prisma validate\nbunx prisma migrate dev\nbunx prisma generate\n```\n\n```text\nthread 'tokio-runtime-worker' panicked at query-engine/connectors/sql-query-connector/src/database/operations/write.rs:194:22:\nCould not figure out an ID in create\nstack backtrace:\n   0:     0xffff62e79450 - <unknown>\n   1:     0xffff627db750 - <unknown>\n   2:     0xffff62e5afb4 - <unknown>\n   3:     0xffff62e7cfc4 - <unknown>\n   4:     0xffff62e7c968 - <unknown>\n```\n\n```text\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    result  {\"testcase id\": \"test-1\", \"testset id\": \"test-set-0\", \"passed\": \"true\"}\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    starting test for of    {\"test case\": \"test-2\", \"test set\": \"test-set-0\"}\nTestrun failed for testcase with id: \"test-2\"\n\n--------------------------------------------------------------------\n\n+-------------------------------------------------------------------------------------------------------------+\n|                                                DIFFS TEST-2                                                 |\n+-------------------------------------------------------------------------------------------------------------+\n|                     EXPECT HEADER                    |                   ACTUAL HEADER                      |\n| -----------------------------------------------------+----------------------------------------------------- |\n|                                                      |                                                      |\n|                                                                                                             |\n|                      EXPECT BODY                     |                    ACTUAL BODY                       |\n| -----------------------------------------------------+----------------------------------------------------- |\n|    {                                                 |  {                                                   |\n|      \"message\": \"User logged in successfully\",       |    \"message\": \"User logged in successfully\",         |\n|   -  \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. | +  \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.   |\n|   eyJpZCI6MSwiZW1haWwiOiJpc3NzYWxjdXBuYW1kZUBhYmMuY2 | eyJpZCI6MSwiZW1haWwiOiJpc3NzYWxjdXBuYW1kZUBhYmMuY2   |\n|   9tIiwiaWF0IjoxNzE5ODIwNDE2LCJleHAiOjE3MTk5MDY4MTZ9 | 9tIiwiaWF0IjoxNzE5ODIwNzIyLCJleHAiOjE3MTk5MDcxMjJ9   |\n|   .vPfugYdsBOlI-0LCdmLKADEEjRXz6FViBRWTJCKQTq8\"      | ._q0QLMJ-6_Y588JLq3fzc3qtBwYEKzdnAQe9z-4PeeQ\"        |\n|    }                                                 |  }                                                   |\n|                                                      |                                                      |\n|                                                                                                             |\n+-------------------------------------------------------------------------------------------------------------+\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    result  {\"testcase id\": \"test-2\", \"testset id\": \"test-set-0\", \"passed\": \"false\"}\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    starting test for of    {\"test case\": \"test-3\", \"test set\": \"test-set-0\"}\nTestrun passed for testcase with id: \"test-3\"\n\n--------------------------------------------------------------------\n\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    result  {\"testcase id\": \"test-3\", \"testset id\": \"test-set-0\", \"passed\": \"true\"}\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    starting test for of    {\"test case\": \"test-4\", \"test set\": \"test-set-0\"}\nTestrun passed for testcase with id: \"test-4\"\n\n--------------------------------------------------------------------\n\n🐰 Keploy: 2024-07-01T13:28:42+05:30    INFO    result  {\"testcase id\": \"test-4\", \"testset id\": \"test-set-0\", \"passed\": \"true\"}\n\n <=========================================> \n  TESTRUN SUMMARY. For test-set: \"test-set-0\"\n        Total tests: 4\n        Total test passed: 3\n        Total test failed: 1\n <=========================================>\n```\n\n```text\npreparedQueryStatement\n```\n\n```text\nS\n```\n\n```text\n--freeze-time\n```\n\n========================================\n\nComments:\n- As I'm interested in learning more about Bun and Keploy, I pulled your repo, but the app can't be started with your instructions. When starting Docker Compose, there's an error `\"Error response from daemon: network keploy-network not found\"`\n- You need to have keploy on your system:- `curl --silent -O -L https:&#47;&#47;keploy.io&#47;install.sh && source install.sh`\n- I used Homebrew to install Keploy - perhaps there's some misconfiguration in the formula.\n- Maybe it's outdated, i'll also try from homebrew to see the issue and maybe report to team.","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":237,"estimatedTokens":2136}}32{"id":"stack-71163623","source":"stackoverflow","questionId":71163623,"title":"How to split Prisma Model into separate file?","tags":["sql","node.js","typescript","orm","prisma"],"text":"Title: How to split Prisma Model into separate file?\nTags: sql, node.js, typescript, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm learning Prisma ORM from video tutorials and official docs. They are explain and write All model code in one file called `schema.prisma`. It's ok but, when application grow it became messy. So, how should I separate my Model definition into separate file?\n\n========================================\n\nTop Answer:\nAt this point in time Prisma doesn't support file segmentation. I can recommend 3 solutions though.\n\n**Option 1: Prismix**\n\nPrismix utilizes models and enums to create relations across files for your Prisma schema via a prismix configuration file.\n\n```\n{\n \"mixers\": [\n {\n \"input\": [\n \"base.prisma\",\n \"./modules/auth/auth.prisma\", \n \"./modules/posts/posts.prisma\",\n ],\n \"output\": \"prisma/schema.prisma\"\n }\n ]\n}\n```\n\nPlacing this inside of a prismix.config.json file which will define how you'd like to merge your Prisma segmentations.\n\n**Option 2: Schemix**\n\nSchemix Utilizes Typescript configurations to handle schema segmenting.\n\nFor example:\n\n```\n// _schema.ts\nimport { createSchema } from \"schemix\";\n\nexport const PrismaSchema = createSchema({\n datasource: {\n provider: \"postgresql\",\n url: {\n env: \"DATABASE_URL\"\n },\n },\n generator: {\n provider: \"prisma-client-js\",\n },\n});\n\nexport const UserModel = PrismaSchema.createModel(\"User\");\n\nimport \"./models/User.model\";\n\nPrismaSchema.export(\"./\", \"schema\");\n```\n\nInside of User.model\n\n```\n// models/User.model.ts\n\nimport { UserModel, PostModel, PostTypeEnum } from \"../_schema\";\n\nUserModel\n .string(\"id\", { id: true, default: { uuid: true } })\n .int(\"registrantNumber\", { default: { autoincrement: true } })\n .boolean(\"isBanned\", { default: false })\n .relation(\"posts\", PostModel, { list: true })\n .raw('@@map(\"service_user\")');\n```\n\nThis will then generate your prisma/schema.prisma containing your full schema. I used only one database as an example (taken from documentation) but you should get the point.\n\n**Option 3:** Cat -> Generate\n\nSegmenting your schema into chunk part filenames and run:\n\n```\ncat *.part.prisma > schema.prisma\nyarn prisma generate\n```\n\nMost of these if not all of them are referenced here in the currently Open issue regarding support for Prisma schema file segmentation https://github.com/prisma/prisma/issues/2377\n\n========================================\n\nCode:\n```text\nschema.prisma\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"prismaSchemaFolder\"]\n}\n```\n\n```text\n{\n  \"mixers\": [\n    {\n        \"input\": [\n            \"base.prisma\",\n            \"./modules/auth/auth.prisma\", \n            \"./modules/posts/posts.prisma\",\n        ],\n        \"output\": \"prisma/schema.prisma\"\n    }\n  ]\n}\n```\n\n```text\n// _schema.ts\nimport { createSchema } from \"schemix\";\n\nexport const PrismaSchema = createSchema({\n  datasource: {\n    provider: \"postgresql\",\n    url: {\n      env: \"DATABASE_URL\"\n    },\n  },\n  generator: {\n    provider: \"prisma-client-js\",\n  },\n});\n\nexport const UserModel = PrismaSchema.createModel(\"User\");\n\nimport \"./models/User.model\";\n\nPrismaSchema.export(\"./\", \"schema\");\n```\n\n```text\n// models/User.model.ts\n\nimport { UserModel, PostModel, PostTypeEnum } from \"../_schema\";\n\nUserModel\n  .string(\"id\", { id: true, default: { uuid: true } })\n  .int(\"registrantNumber\", { default: { autoincrement: true } })\n  .boolean(\"isBanned\", { default: false })\n  .relation(\"posts\", PostModel, { list: true })\n  .raw('@@map(\"service_user\")');\n```\n\n```text\ncat *.part.prisma > schema.prisma\nyarn prisma generate\n```\n\n```json\n// package.json\n\"scripts\": {\n  \"prisma-concat\": \"npx ts-node prisma/concat-schemas.ts && npx prisma format\",\n  \"generate\": \"yarn prisma-concat && npx prisma generate\",\n}\n```\n\n```text\n// connect-db.prisma\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n```js\n// prisma/concat-schemas.ts\n\nimport { appendFile, readFile, writeFile } from 'fs/promises'\nimport { glob } from 'glob'\n\nconst start = async () => {\n  const schemaFile = 'prisma/schema.prisma'\n  const connectFile = 'prisma/connect-db.prisma'\n  const models = await glob('src/**/*.prisma')\n  const files = [connectFile, ...models]\n\n  await writeFile(schemaFile, '')\n\n  await Promise.all(\n    files.map(async (path) => {\n      const content = await readFile(path)\n      return appendFile(schemaFile, content.toString())\n    }),\n  )\n}\nstart()\n```\n\n```text\nyarn add -g glob\n```\n\n```text\nyarn generate\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- but I can't keep in folders? For example, If I want to keep customer related in one folder what can we do? Example: prisma/customer/customer.primsa prisma/customer/customerLocations.primsa prisma/customer/customeTransactions.primsa is that possible?","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":218,"estimatedTokens":1280}}33{"id":"stack-72583324","source":"stackoverflow","questionId":72583324,"title":"How to make id autoincrement in schema.prisma?","tags":["postgresql","prisma"],"text":"Title: How to make id autoincrement in schema.prisma?\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am writing a postgreSQL database. The ID must be auto-incrementing.\n\n```\nmodel User {\n id String @id @default(cuid())\n name String?\n email String? @unique\n emailVerified DateTime? @map(\"email_verified\")\n image String?\n createdAt DateTime @default(now()) @map(name: \"created_at\")\n updatedAt DateTime @updatedAt @map(name: \"updated_at\")\n posts Post[]\n accounts Account[]\n sessions Session[]\n\n @@map(name: \"users\")\n}\n```\n\nResult\n\nIf you write the ID manually, you can enter any value as in the first entry, but autocomplete generates the code as in the second entry. I got the code from the site Vercel.\n\n========================================\n\nCode:\n```text\nmodel User {\n id            String    @id @default(cuid())\n name          String?\n email         String?   @unique\n emailVerified DateTime? @map(\"email_verified\")\n image         String?\n createdAt     DateTime  @default(now()) @map(name: \"created_at\")\n updatedAt     DateTime  @updatedAt @map(name: \"updated_at\")\n posts         Post[]\n accounts      Account[]\n sessions      Session[]\n\n @@map(name: \"users\")\n}\n```\n\n```text\nmodel User {\n id            Int       @id @default(autoincrement())\n name          String?\n email         String?   @unique\n emailVerified DateTime? @map(\"email_verified\")\n image         String?\n createdAt     DateTime  @default(now()) @map(name: \"created_at\")\n updatedAt     DateTime  @updatedAt @map(name: \"updated_at\")\n posts         Post[]\n accounts      Account[]\n sessions      Session[]\n\n @@map(name: \"users\")\n}\n```\n\n```text\nUser\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":68,"estimatedTokens":409}}34{"id":"stack-75413452","source":"stackoverflow","questionId":75413452,"title":"How do I use next auth getServerSession in next js 13 beta server component in app directory","tags":["session","jwt","prisma","next.js13","next-auth"],"text":"Title: How do I use next auth getServerSession in next js 13 beta server component in app directory\nTags: session, jwt, prisma, next.js13, next-auth\nSource: Stack Overflow\n\nQuestion:\nI'm using next auth v4 with next js 13 beta with server component, and everything works fine. But I have a situation where I will need to know the logged user id, since I'm using next auth, I have access to the session, I can use useSession() but then I will need to make the component a client component, So I want to use it on the server, I can use getServerSession in API since I have access to req & res object, but in next js beta with new app dir, I can't do it. Please let me know if you know how to fix the issue. Thank you\n\n```\nimport { getServerSession } from \"next-auth\";\nimport { authOptions } from \"@/pages/api/auth/[...nextauth]\";\n\nconst Test = async () => {\n const user_id = 1; // How do I get user id from session, user_id is available in session\n\n // I don't have access req & res object in server component.\n const data = await getServerSession(request, response, authOptions);\n\n console.log(data);\n\n});\n return (\n <>\n );\n};\n\nexport default Test;\n```\n\nDidn't find enough information\n\n========================================\n\nTop Answer:\nDocs for Options\n\n```\nimport { NextAuthOptions } from 'next-auth'\nimport { getServerSession } from 'next-auth'\n```\n\nthis is the NextAuthOptions type\n\n```\nexport interface AuthOptions {\n providers: Provider[];\n secret?: string;\n session?: Partial;\n jwt?: Partial;\n pages?: Partial;\n callbacks?: Partial;\n events?: Partial;\n adapter?: Adapter;\n debug?: boolean;\n logger?: Partial;\n theme?: Theme;\n useSecureCookies?: boolean;\n cookies?: Partial;\n}\n```\n\nthis is how you get the session\n\n```\nconst session = await getServerSession(authOptions)\n```\n\nBased on AuthOptions interface\n\n```\nconst authOption: NextAuthOptions = {\n // Since you tagged prisma\n adapter: PrismaAdapter(yourDbConfig),\n session: {\n strategy: 'jwt',\n },\n // https://next-auth.js.org/configuration/pages\n pages: {\n signIn: '/login',\n },\n providers: [\n GoogleProvider({\n clientId: clientId,\n clientSecret: clientSecret,\n }),\n ],\n callbacks: {\n async session({ token, session }) {\n if (token) {\n // set session here\n }\n return session\n },\n async jwt({ token, user }) {\n const dbUser = getUserByTokenEmail\n //add logic here\n },\n },\n}\n```\n\nthis is how we use `authOptions` to set up next-auth\n\n```\n// app/auth/[...nextauth].ts (I think after next 13.2)\n// pages/api/auth/[...nextauth].ts before\n \nimport { authOptions } from 'folderLocationOfauthOptions'\nimport NextAuth from 'next-auth'\n \nexport default NextAuth(authOptions)\n```\n\n========================================\n\nCode:\n```text\nimport { getServerSession } from \"next-auth\";\nimport { authOptions } from \"@/pages/api/auth/[...nextauth]\";\n\nconst Test = async () => {\n    const user_id = 1; // How do I get user id from session, user_id is available in session\n\n    // I don't have access req & res object in server component.\n    const data = await getServerSession(request, response, authOptions);\n\n    console.log(data);\n\n});\n    return (\n        <></>\n    );\n};\n\nexport default Test;\n```\n\n```text\nimport { getServerSession } from \"next-auth\";\nimport { authOptions } from \"@/pages/api/auth/[...nextauth]\";\n\nconst Test = async () => {\n\n    const data = await getServerSession(authOptions);\n\n    console.log(data);\n\n});\n    return (\n        <></>\n    );\n};\n\nexport default Test;\n```\n\n```js\nimport { NextAuthOptions } from 'next-auth'\nimport { getServerSession } from 'next-auth'\n```\n\n```js\nexport interface AuthOptions {\n  providers: Provider[];\n  secret?: string;\n  session?: Partial<SessionOptions>;\n  jwt?: Partial<JWTOptions>;\n  pages?: Partial<PagesOptions>;\n  callbacks?: Partial<CallbacksOptions>;\n  events?: Partial<EventCallbacks>;\n  adapter?: Adapter;\n  debug?: boolean;\n  logger?: Partial<LoggerInstance>;\n  theme?: Theme;\n  useSecureCookies?: boolean;\n  cookies?: Partial<CookiesOptions>;\n}\n```\n\n```js\nconst session = await getServerSession(authOptions)\n```\n\n```js\nconst authOption: NextAuthOptions = {\n  // Since you tagged prisma\n  adapter: PrismaAdapter(yourDbConfig),\n  session: {\n    strategy: 'jwt',\n  },\n  // https://next-auth.js.org/configuration/pages\n  pages: {\n    signIn: '/login',\n  },\n  providers: [\n    GoogleProvider({\n      clientId: clientId,\n      clientSecret: clientSecret,\n    }),\n  ],\n  callbacks: {\n    async session({ token, session }) {\n      if (token) {\n        // set session here\n      }\n      return session\n    },\n    async jwt({ token, user }) {\n      const dbUser = getUserByTokenEmail\n           //add logic here\n    },\n  },\n}\n```\n\n```js\n// app/auth/[...nextauth].ts (I think after next 13.2)\n// pages/api/auth/[...nextauth].ts before\n    \nimport { authOptions } from 'folderLocationOfauthOptions'\nimport NextAuth from 'next-auth'\n    \nexport default NextAuth(authOptions)\n```\n\n```text\nauthOptions\n```\n\n```text\nauthOptions\n```\n\n```text\napp/api/auth/[...nextauth]/route.(ts/js)\n```\n\n```text\nimport NextAuth from 'next-auth'\nimport GoogleProvider from 'next-auth/providers/google'\n\nconst handler = NextAuth({\n  providers: [\n    GoogleProvider({\n      clientId: process.env.GOOGLE_CLIENT_ID,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET\n    })\n  ]\n})\n\nexport { handler as GET, handler as POST }\n```\n\n```text\nimport { getServerSession } from 'next-auth'\n\n...\n\nexport default async function Layout ({ children }) {\n  const data = await getServerSession()\n\n  return (\n    <h5>Data: {JSON.stringify(data)}</h5>\n  )\n}\n```\n\n```text\nsrc/app/api/auth/[...nextauth]/route.js\n```\n\n```text\ngetServerSession\n```\n\n```text\nsrc/app/layout.js\n```\n\n========================================\n\nComments:\n- Mind sharing your authOptions?\n- [gist.github.com/shakibhasan09/&hellip; this\n- I am having the same issue. Does that link still work? I am getting 404.\n- [gist.github.com/shakibhasan09/c37eb67910a992f881e722313531b&zwnj;&#8203;2fb]\n- Another 404 - would you mind sharing your authOptions in the post?\n- @DavidConlisk, sure gist.github.com/shakibhasan09/c37eb67910a992f881e722313531b2&zwnj;&#8203;fb\n- This displays a message in the server console. Not sure if it's a warning: ``getServerSession` is used in a React Server Component.`\n- i need request in my auth options :/\n- Oh, thank you, very detailed. Although, having just started all this, the file structure is causing me some headache. If we're to be migrating away from /pages/api/auth/[...nextauth].js, where are all these config and functions supposed to go?\n- @mtro this is exactly what I'm trying to understand at the moment as well. Any luck?\n- @Laky we are not migrating away `[...nextauth].js`. updated the answer\n- @Yilmaz I actually tried the same configuration you placed here, with NextJS 13 app router. I have no luck .. keeps getting unauthenticated.\n- @TommyLeong have you configured correctly? Did you wrap the app with the auth provider\n- Yes I did, I also tried passing in the session to SessionProvider. I'll setup a post and come back with link for better clarity.\n- Hi @priyabagus, interesting way of getting `serversession` from `rootlayout`. Im also with NextJs 13, app router... with your technique here, im still getting `{ user: { name: undefined, email: undefined, image: undefined } }`\n- @TommyLeong Have you tried logging in?\n- Yes I did. In fact at this moment, when I enable PrismaAdapter it will always keep me as unauthenticated.\n- This is one of the easiest ways to do auth on the server-rendered components and pages","metadata":{"transformedAt":"2026-08-18T18:33:14.815Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":299,"estimatedTokens":1876}}35{"id":"stack-79553495","source":"stackoverflow","questionId":79553495,"title":"throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);","tags":["node.js","typescript","express","prisma"],"text":"Title: throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);\nTags: node.js, typescript, express, prisma\nSource: Stack Overflow\n\nQuestion:\nGadget Controller Ts Code :\n\n```\nimport { Request, Response, NextFunction } from 'express';\nimport { Status } from '@prisma/client'\nimport prisma from '../utils/prisma.client';\nimport { AppError } from '../utils/error.handler';\n\n// Generate random codename for gadgets\nconst generateCodename = (): string => {\n const adjectives = ['Mighty', 'Silent', 'Phantom', 'Shadow', 'Stealth', 'Covert', 'Invisible', 'Deadly', 'Rapid', 'Quantum'];\n const nouns = ['Eagle', 'Panther', 'Cobra', 'Viper', 'Falcon', 'Wolf', 'Hawk', 'Tiger', 'Raven', 'Phoenix'];\n \n const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];\n const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];\n \n return `The ${randomAdjective} ${randomNoun}`;\n};\n\n// Generate random mission success probability\nconst generateMissionProbability = (): number => {\n return Math.floor(Math.random() * 100);\n};\n\n// Get all gadgets with optional status filter\nexport const getAllGadgets = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const { status } = req.query;\n \n const whereClause = status ? { status: status as Status } : {};\n \n const gadgets = await prisma.gadget.findMany({\n where: whereClause\n });\n \n const gadgetsWithProbability = gadgets.map(gadget => ({\n ...gadget,\n missionSuccessProbability: generateMissionProbability()\n }));\n \n res.status(200).json({\n status: 'success',\n results: gadgetsWithProbability.length,\n data: {\n gadgets: gadgetsWithProbability\n }\n });\n } catch (error) {\n next(error);\n }\n};\n\n// Create a new gadget\nexport const createGadget = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const { status } = req.body;\n \n const gadget = await prisma.gadget.create({\n data: {\n name: generateCodename(),\n status: status || 'Available'\n }\n });\n \n res.status(201).json({\n status: 'success',\n data: {\n gadget\n }\n });\n } catch (error) {\n next(error);\n }\n};\n\n// Update a gadget\nexport const updateGadget = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const { id } = req.params;\n const { name, status } = req.body;\n \n const gadget = await prisma.gadget.findUnique({\n where: { id }\n });\n \n if (!gadget) {\n return next(new AppError('No gadget found with that ID', 404));\n }\n \n const updatedGadget = await prisma.gadget.update({\n where: { id },\n data: {\n name,\n status\n }\n });\n \n res.status(200).json({\n status: 'success',\n data: {\n gadget: updatedGadget\n }\n });\n } catch (error) {\n next(error);\n }\n};\n\n// Decommission a gadget (soft delete)\nexport const decommissionGadget = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const { id } = req.params;\n \n const gadget = await prisma.gadget.findUnique({\n where: { id }\n });\n \n if (!gadget) {\n return next(new AppError('No gadget found with that ID', 404));\n }\n \n const decommissionedGadget = await prisma.gadget.update({\n where: { id },\n data: {\n status: 'Decommissioned',\n decomissionedAt: new Date()\n }\n });\n \n res.status(200).json({\n status: 'success',\n data: {\n gadget: decommissionedGadget\n }\n });\n } catch (error) {\n next(error);\n }\n};\n\n// Trigger self-destruct sequence for a gadget\nexport const selfDestructGadget = async (req: Request, res: Response, next: NextFunction) => {\n try {\n const { id } = req.params;\n \n const gadget = await prisma.gadget.findUnique({\n where: { id }\n });\n \n if (!gadget) {\n return next(new AppError('No gadget found with that ID', 404));\n }\n \n // Generate confirmation code\n const confirmationCode = Math.floor(100000 + Math.random() * 900000);\n \n const updatedGadget = await prisma.gadget.update({\n where: { id },\n data: {\n status: 'Destroyed',\n selfDestruct: new Date()\n }\n });\n \n res.status(200).json({\n status: 'success',\n confirmationCode,\n message: 'Self-destruct sequence initiated',\n data: {\n gadget: updatedGadget\n }\n });\n } catch (error) {\n next(error);\n }\n};\n```\n\n```\nThe Gadgets Routes : \nrouter.get('/', getAllGadgets);\nrouter.post('/', createGadget);\nrouter.patch('/:id', updateGadget);\nrouter.delete('/:id', decommissionGadget);\nrouter.post('/:id/self-destruct', selfDestructGadget);\n```\n\nEven though i have no error in the routing , still i am getting the error :\n\nthrow new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);\n^\nTypeError: Missing parameter name at 1: https://git.new/pathToRegexpError\n\nI possibly tried everything , GPT , V0 , StackOverFlow but the solutions didn't work.\n\nHere is the package.json :\n\n```\n{\n \"name\": \"pg_imp\",\n \"version\": \"1.0.0\",\n \"main\": \"dist/index.js\",\n \"scripts\": {\n \"start\": \"node dist/index.js\",\n \"dev\": \"ts-node-dev --respawn --transpile-only src/index.ts\",\n \"build\": \"tsc\",\n \"prisma:generate\": \"prisma generate\",\n \"prisma:migrate\": \"prisma migrate dev --name init\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\",\n \"description\": \"\",\n \"devDependencies\": {\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cors\": \"^2.8.17\",\n \"@types/express\": \"^5.0.1\",\n \"@types/jsonwebtoken\": \"^9.0.9\",\n \"@types/uuid\": \"^10.0.0\",\n \"prisma\": \"^6.5.0\",\n \"ts-node-dev\": \"^2.0.0\",\n \"typescript\": \"^5.8.2\"\n },\n \"dependencies\": {\n \"@prisma/client\": \"^6.5.0\",\n \"bcrypt\": \"^5.1.1\",\n \"cors\": \"^2.8.5\",\n \"dotenv\": \"^16.4.7\",\n \"express\": \"^5.1.0\",\n \"express-validator\": \"^7.2.1\",\n \"helmet\": \"^8.1.0\",\n \"jsonwebtoken\": \"^9.0.2\",\n \"pg\": \"^8.14.1\",\n \"uuid\": \"^11.1.0\"\n }\n}\n```\n\nCan somebody please tell , how to fix the bug ! i am unable to fix this since 48Hrs (Skill Issue)\n\nI have tried downgrading the Express version to 4 because some said the Express vr:5 is causing the error , but that didnt help ,\n\ni checked all the routes & api endpoints but that didn't help either.\n\nGadget Routes :\n\n```\n// src/routes/gadget.routes.ts\nimport { Router } from 'express';\nimport { \n getAllGadgets, \n createGadget, \n updateGadget, \n decommissionGadget, \n selfDestructGadget \n} from '../controllers/gadget.controller';\nimport { protect } from '../middleware/auth.middleware';\n\nconst router = Router();\n\n// Apply authentication middleware to all routes\nrouter.use(protect);\n\n// Routes\nrouter.get('/', getAllGadgets);\nrouter.post('/', createGadget);\nrouter.patch('/:id', updateGadget);\nrouter.delete('/:id', decommissionGadget);\nrouter.post('/:id/self-destruct', selfDestructGadget);\n\nexport default router;\n```\n\napp.ts :\n\n```\nimport express, { Request, Response, NextFunction } from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport authRoutes from './routes/auth.routes';\nimport gadgetRoutes from './routes/gadget.routes';\nimport { AppError, handleError } from './utils/error.handler';\n\nconst app = express();\n\n// Middleware\napp.use(helmet());\napp.use(cors());\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\n// Routes\napp.use('/api/auth', authRoutes);\napp.use('/api/gadgets', gadgetRoutes);\n\n// Health check route\napp.get('/health', (req, res) => {\n res.status(200).json({ status: 'success', message: 'API is running' });\n});\n\n// Handle undefined routes\napp.all('*', (req, res, next) => {\n next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));\n});\n\n// Global error handler\napp.use((err: any, req: Request, res: Response, next: NextFunction) => {\n handleError(err, res);\n});\n\nexport default app;\n```\n\nauth_routes.ts :\n\n```\nimport { Router } from 'express';\nimport { body } from 'express-validator';\nimport { register, login } from '../controllers/auth.controller';\nimport { validate } from '../middleware/validate.middleware';\n\nconst router = Router();\n\n// Validation rules\nconst registerValidation = [\n body('username')\n .notEmpty().withMessage('Username is required')\n .isLength({ min: 3 }).withMessage('Username must be at least 3 characters long'),\n body('password')\n .notEmpty().withMessage('Password is required')\n .isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')\n];\n\nconst loginValidation = [\n body('username').notEmpty().withMessage('Username is required'),\n body('password').notEmpty().withMessage('Password is required')\n];\n\n// Routes\nrouter.post('/register', validate(registerValidation), register);\nrouter.post('/login', validate(loginValidation), login);\n\nexport default router;\n```\n\nAuth_Middlewaree.ts :\n\n```\nimport { Request, Response, NextFunction } from 'express';\nimport jwt from 'jsonwebtoken';\nimport { AppError } from '../utils/error.handler';\nimport prisma from '../utils/prisma.client';\n\ninterface JwtPayload {\n id: string;\n}\n\ndeclare global {\n namespace Express {\n interface Request {\n user?: {\n id: string;\n };\n }\n }\n}\n\nexport const protect = async (req: Request, res: Response, next: NextFunction) => {\n try {\n // 1) Get token and check if it exists\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];\n }\n\n if (!token) {\n return next(new AppError('You are not logged in. Please log in to get access', 401));\n }\n\n // 2) Verify token\n const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as JwtPayload;\n\n // 3) Check if user still exists\n const user = await prisma.user.findUnique({\n where: { id: decoded.id }\n });\n\n if (!user) {\n return next(new AppError('The user belonging to this token no longer exists', 401));\n }\n\n // 4) Grant access to protected route\n req.user = { id: user.id };\n next();\n } catch (error) {\n next(new AppError('Invalid token. Please log in again', 401));\n }\n};\n```\n\n========================================\n\nTop Answer:\nThe answer didn't work for me, I had to roll back to Express 4 (`4.21.2`), but I'm on a legacy project upgrading from Angular `10` -> `17`, etc. Will update the answer if/when will get a better one!\n\nI'm on node `v20.14.0`, and Cursor Pro - yes, it also didn't fix it. Additionally, created a brand new hello world Express project, and still have seen the same problem on Express `5`.\n\n========================================\n\nCode:\n```text\nimport { Request, Response, NextFunction } from 'express';\nimport { Status } from '@prisma/client'\nimport prisma from '../utils/prisma.client';\nimport { AppError } from '../utils/error.handler';\n\n// Generate random codename for gadgets\nconst generateCodename = (): string => {\n  const adjectives = ['Mighty', 'Silent', 'Phantom', 'Shadow', 'Stealth', 'Covert', 'Invisible', 'Deadly', 'Rapid', 'Quantum'];\n  const nouns = ['Eagle', 'Panther', 'Cobra', 'Viper', 'Falcon', 'Wolf', 'Hawk', 'Tiger', 'Raven', 'Phoenix'];\n  \n  const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];\n  const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];\n  \n  return `The ${randomAdjective} ${randomNoun}`;\n};\n\n// Generate random mission success probability\nconst generateMissionProbability = (): number => {\n  return Math.floor(Math.random() * 100);\n};\n\n// Get all gadgets with optional status filter\nexport const getAllGadgets = async (req: Request, res: Response, next: NextFunction) => {\n  try {\n    const { status } = req.query;\n    \n    const whereClause = status ? { status: status as Status } : {};\n    \n    const gadgets = await prisma.gadget.findMany({\n      where: whereClause\n    });\n    \n    const gadgetsWithProbability = gadgets.map(gadget => ({\n      ...gadget,\n      missionSuccessProbability: generateMissionProbability()\n    }));\n    \n    res.status(200).json({\n      status: 'success',\n      results: gadgetsWithProbability.length,\n      data: {\n        gadgets: gadgetsWithProbability\n      }\n    });\n  } catch (error) {\n    next(error);\n  }\n};\n\n// Create a new gadget\nexport const createGadget = async (req: Request, res: Response, next: NextFunction) => {\n  try {\n    const { status } = req.body;\n    \n    const gadget = await prisma.gadget.create({\n      data: {\n        name: generateCodename(),\n        status: status || 'Available'\n      }\n    });\n    \n    res.status(201).json({\n      status: 'success',\n      data: {\n        gadget\n      }\n    });\n  } catch (error) {\n    next(error);\n  }\n};\n\n// Update a gadget\nexport const updateGadget = async (req: Request, res: Response, next: NextFunction) => {\n  try {\n    const { id } = req.params;\n    const { name, status } = req.body;\n    \n    const gadget = await prisma.gadget.findUnique({\n      where: { id }\n    });\n    \n    if (!gadget) {\n      return next(new AppError('No gadget found with that ID', 404));\n    }\n    \n    const updatedGadget = await prisma.gadget.update({\n      where: { id },\n      data: {\n        name,\n        status\n      }\n    });\n    \n    res.status(200).json({\n      status: 'success',\n      data: {\n        gadget: updatedGadget\n      }\n    });\n  } catch (error) {\n    next(error);\n  }\n};\n\n// Decommission a gadget (soft delete)\nexport const decommissionGadget = async (req: Request, res: Response, next: NextFunction) => {\n  try {\n    const { id } = req.params;\n    \n    const gadget = await prisma.gadget.findUnique({\n      where: { id }\n    });\n    \n    if (!gadget) {\n      return next(new AppError('No gadget found with that ID', 404));\n    }\n    \n    const decommissionedGadget = await prisma.gadget.update({\n      where: { id },\n      data: {\n        status: 'Decommissioned',\n        decomissionedAt: new Date()\n      }\n    });\n    \n    res.status(200).json({\n      status: 'success',\n      data: {\n        gadget: decommissionedGadget\n      }\n    });\n  } catch (error) {\n    next(error);\n  }\n};\n\n// Trigger self-destruct sequence for a gadget\nexport const selfDestructGadget = async (req: Request, res: Response, next: NextFunction) => {\n  try {\n    const { id } = req.params;\n    \n    const gadget = await prisma.gadget.findUnique({\n      where: { id }\n    });\n    \n    if (!gadget) {\n      return next(new AppError('No gadget found with that ID', 404));\n    }\n    \n    // Generate confirmation code\n    const confirmationCode = Math.floor(100000 + Math.random() * 900000);\n    \n    const updatedGadget = await prisma.gadget.update({\n      where: { id },\n      data: {\n        status: 'Destroyed',\n        selfDestruct: new Date()\n      }\n    });\n    \n    res.status(200).json({\n      status: 'success',\n      confirmationCode,\n      message: 'Self-destruct sequence initiated',\n      data: {\n        gadget: updatedGadget\n      }\n    });\n  } catch (error) {\n    next(error);\n  }\n};\n```\n\n```text\nThe Gadgets Routes : \nrouter.get('/', getAllGadgets);\nrouter.post('/', createGadget);\nrouter.patch('/:id', updateGadget);\nrouter.delete('/:id', decommissionGadget);\nrouter.post('/:id/self-destruct', selfDestructGadget);\n```\n\n```text\n{\n  \"name\": \"pg_imp\",\n  \"version\": \"1.0.0\",\n  \"main\": \"dist/index.js\",\n  \"scripts\": {\n    \"start\": \"node dist/index.js\",\n    \"dev\": \"ts-node-dev --respawn --transpile-only src/index.ts\",\n    \"build\": \"tsc\",\n    \"prisma:generate\": \"prisma generate\",\n    \"prisma:migrate\": \"prisma migrate dev --name init\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"description\": \"\",\n  \"devDependencies\": {\n    \"@types/bcrypt\": \"^5.0.2\",\n    \"@types/cors\": \"^2.8.17\",\n    \"@types/express\": \"^5.0.1\",\n    \"@types/jsonwebtoken\": \"^9.0.9\",\n    \"@types/uuid\": \"^10.0.0\",\n    \"prisma\": \"^6.5.0\",\n    \"ts-node-dev\": \"^2.0.0\",\n    \"typescript\": \"^5.8.2\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"^6.5.0\",\n    \"bcrypt\": \"^5.1.1\",\n    \"cors\": \"^2.8.5\",\n    \"dotenv\": \"^16.4.7\",\n    \"express\": \"^5.1.0\",\n    \"express-validator\": \"^7.2.1\",\n    \"helmet\": \"^8.1.0\",\n    \"jsonwebtoken\": \"^9.0.2\",\n    \"pg\": \"^8.14.1\",\n    \"uuid\": \"^11.1.0\"\n  }\n}\n```\n\n```text\n// src/routes/gadget.routes.ts\nimport { Router } from 'express';\nimport { \n  getAllGadgets, \n  createGadget, \n  updateGadget, \n  decommissionGadget, \n  selfDestructGadget \n} from '../controllers/gadget.controller';\nimport { protect } from '../middleware/auth.middleware';\n\nconst router = Router();\n\n// Apply authentication middleware to all routes\nrouter.use(protect);\n\n// Routes\nrouter.get('/', getAllGadgets);\nrouter.post('/', createGadget);\nrouter.patch('/:id', updateGadget);\nrouter.delete('/:id', decommissionGadget);\nrouter.post('/:id/self-destruct', selfDestructGadget);\n\nexport default router;\n```\n\n```text\nimport express, { Request, Response, NextFunction } from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport authRoutes from './routes/auth.routes';\nimport gadgetRoutes from './routes/gadget.routes';\nimport { AppError, handleError } from './utils/error.handler';\n\nconst app = express();\n\n// Middleware\napp.use(helmet());\napp.use(cors());\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\n// Routes\napp.use('/api/auth', authRoutes);\napp.use('/api/gadgets', gadgetRoutes);\n\n// Health check route\napp.get('/health', (req, res) => {\n  res.status(200).json({ status: 'success', message: 'API is running' });\n});\n\n// Handle undefined routes\napp.all('*', (req, res, next) => {\n  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));\n});\n\n// Global error handler\napp.use((err: any, req: Request, res: Response, next: NextFunction) => {\n  handleError(err, res);\n});\n\nexport default app;\n```\n\n```text\nimport { Router } from 'express';\nimport { body } from 'express-validator';\nimport { register, login } from '../controllers/auth.controller';\nimport { validate } from '../middleware/validate.middleware';\n\nconst router = Router();\n\n// Validation rules\nconst registerValidation = [\n  body('username')\n    .notEmpty().withMessage('Username is required')\n    .isLength({ min: 3 }).withMessage('Username must be at least 3 characters long'),\n  body('password')\n    .notEmpty().withMessage('Password is required')\n    .isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')\n];\n\nconst loginValidation = [\n  body('username').notEmpty().withMessage('Username is required'),\n  body('password').notEmpty().withMessage('Password is required')\n];\n\n// Routes\nrouter.post('/register', validate(registerValidation), register);\nrouter.post('/login', validate(loginValidation), login);\n\nexport default router;\n```\n\n```text\nimport { Request, Response, NextFunction } from 'express';\nimport jwt from 'jsonwebtoken';\nimport { AppError } from '../utils/error.handler';\nimport prisma from '../utils/prisma.client';\n\ninterface JwtPayload {\n  id: string;\n}\n\ndeclare global {\n  namespace Express {\n    interface Request {\n      user?: {\n        id: string;\n      };\n    }\n  }\n}\n\nexport const protect = async (req: Request, res: Response, next: NextFunction) => {\n  try {\n    // 1) Get token and check if it exists\n    let token;\n    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n      token = req.headers.authorization.split(' ')[1];\n    }\n\n    if (!token) {\n      return next(new AppError('You are not logged in. Please log in to get access', 401));\n    }\n\n    // 2) Verify token\n    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as JwtPayload;\n\n    // 3) Check if user still exists\n    const user = await prisma.user.findUnique({\n      where: { id: decoded.id }\n    });\n\n    if (!user) {\n      return next(new AppError('The user belonging to this token no longer exists', 401));\n    }\n\n    // 4) Grant access to protected route\n    req.user = { id: user.id };\n    next();\n  } catch (error) {\n    next(new AppError('Invalid token. Please log in again', 401));\n  }\n};\n```\n\n```text\nMissing parameter name at ${i}: ${DEBUG_URL}\n```\n\n```js\napp.all('*', (req, res, next) => {})\n```\n\n```js\napp.all('/{*any}', (req, res, next) => {})\n```\n\n```text\n4.21.2\n```\n\n```text\n10\n```\n\n```text\n17\n```\n\n```text\nv20.14.0\n```\n\n```text\n5\n```\n\n```text\napp.all('*id',(req,res,next)=>{   next(new ExpressError(404,\"Page not found\")); });  and my ExpressError file is like this class ExpressError extends Error{     constructor(statusCode,message){         super();         this.statusCode=statusCode;         this.message=message;     } } module.exports = ExpressError;\n```\n\n```text\nnpm install express@4.21.2\n```\n\n========================================\n\nComments:\n- Based on Express Guide expressjs.com/en/guide/migrating-5.html#path-syntax, it can use `app.use('&#47;{*splat}')`. Also, this answer will work fine too (I tested)\n- This error comes on express version above 5 I guess but works fine on 4\n- Your answer really helped me. I had the same error, but now it’s fixed.😍😍","metadata":{"transformedAt":"2026-08-18T18:33:14.816Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":835,"estimatedTokens":5068}}36{"id":"stack-71736148","source":"stackoverflow","questionId":71736148,"title":"Prisma: Error validating datasource `db`: the URL must start with the protocol `postgresql://` or `postgres://`","tags":["prisma"],"text":"Title: Prisma: Error validating datasource `db`: the URL must start with the protocol `postgresql://` or `postgres://`\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy my NestJS application with prisma in production. But when launching my server, I have this error:\n\n```\nnestjs | PrismaClientInitializationError: error: Error validating datasource `db`: the URL must start with the protocol `postgresql://` or `postgres://`.\nnestjs | --> schema.prisma:11\nnestjs | | \nnestjs | 10 | provider = \"postgresql\"\nnestjs | 11 | url = env(\"DATABASE_URL\")\nnestjs | | \nnestjs | \nnestjs | Validation Error Count: 1\nnestjs | at Object.loadEngine (/app/node_modules/@prisma/client/runtime/index.js:35591:19)\nnestjs | at async Object.instantiateLibrary (/app/node_modules/@prisma/client/runtime/index.js:35520:5)\nnestjs | at async Object.start (/app/node_modules/@prisma/client/runtime/index.js:35670:5)\nnestjs | at async Proxy.onModuleInit (/app/dist/prisma.service.js:14:9)\nnestjs | at async Promise.all (index 0)\nnestjs | at async callModuleInitHook (/app/node_modules/@nestjs/core/hooks/on-module-init.hook.js:43:5)\nnestjs | at async NestApplication.callInitHook (/app/node_modules/@nestjs/core/nest-application-context.js:178:13)\nnestjs | at async NestApplication.init (/app/node_modules/@nestjs/core/nest-application.js:96:9)\nnestjs | at async NestApplication.listen (/app/node_modules/@nestjs/core/nest-application.js:155:33)\nnestjs | at async bootstrap (/app/dist/main.js:8:5) {\nnestjs | clientVersion: '3.11.1',\nnestjs | errorCode: 'P1012'\nnestjs | }\n```\n\nMy docker-compose.yml :\n\n```\nversion: \"3.2\"\n\nservices:\n nestjs:\n container_name: nestjs\n build:\n context: ./apps/nestjs\n dockerfile: Dockerfile.prod\n env_file:\n - ./apps/nestjs/.env\n```\n\nMy .env :\n\n```\nDATABASE_URL=\"postgres://myUser:myPassword@myHost:myPort/myDB?sslmode=require\"\n```\n\nWhat I tried to do :\n\n- Check that my `.env` was taken into account. When I go into the container, my environment variable exists\n\n- Try replacing `postgres` to `postgresql`\n\nAny ideas?\n\nThanks you!\n\n========================================\n\nTop Answer:\nyou could use `npm uninstall prisma` then `npm install prisma` and finally `npx prisma generate`.\nThat worked for me. It will create a new prisma client based on your prisma schema file.\n\n========================================\n\nCode:\n```text\nnestjs     | PrismaClientInitializationError: error: Error validating datasource `db`: the URL must start with the protocol `postgresql://` or `postgres://`.\nnestjs     |   -->  schema.prisma:11\nnestjs     |    | \nnestjs     | 10 |   provider          = \"postgresql\"\nnestjs     | 11 |   url               = env(\"DATABASE_URL\")\nnestjs     |    | \nnestjs     | \nnestjs     | Validation Error Count: 1\nnestjs     |     at Object.loadEngine (/app/node_modules/@prisma/client/runtime/index.js:35591:19)\nnestjs     |     at async Object.instantiateLibrary (/app/node_modules/@prisma/client/runtime/index.js:35520:5)\nnestjs     |     at async Object.start (/app/node_modules/@prisma/client/runtime/index.js:35670:5)\nnestjs     |     at async Proxy.onModuleInit (/app/dist/prisma.service.js:14:9)\nnestjs     |     at async Promise.all (index 0)\nnestjs     |     at async callModuleInitHook (/app/node_modules/@nestjs/core/hooks/on-module-init.hook.js:43:5)\nnestjs     |     at async NestApplication.callInitHook (/app/node_modules/@nestjs/core/nest-application-context.js:178:13)\nnestjs     |     at async NestApplication.init (/app/node_modules/@nestjs/core/nest-application.js:96:9)\nnestjs     |     at async NestApplication.listen (/app/node_modules/@nestjs/core/nest-application.js:155:33)\nnestjs     |     at async bootstrap (/app/dist/main.js:8:5) {\nnestjs     |   clientVersion: '3.11.1',\nnestjs     |   errorCode: 'P1012'\nnestjs     | }\n```\n\n```text\nversion: \"3.2\"\n\nservices:\n  nestjs:\n    container_name: nestjs\n    build:\n      context: ./apps/nestjs\n      dockerfile: Dockerfile.prod\n    env_file:\n      - ./apps/nestjs/.env\n```\n\n```text\nDATABASE_URL=\"postgres://myUser:myPassword@myHost:myPort/myDB?sslmode=require\"\n```\n\n```text\n.env\n```\n\n```text\npostgres\n```\n\n```text\npostgresql\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client/edge\";\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\";\n```\n\n```text\nnpm uninstall prisma\n```\n\n```text\nnpm install prisma\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpx prisma migrate dev --name init --create-only \nnpx prisma generate\n```\n\n```text\nNEXT_PUBLIC_DATABASE_URL=postgres://xxxxxxx\n```\n\n```text\nenv\n```\n\n```text\nNEXT_PUBLIC_\n```\n\n```text\nenv\n```\n\n========================================\n\nComments:\n- I found on Mac, i must remove the \"\", but on Windows, the env works fine\n- This did the trick for me! For reference between the differences: github.com/prisma/prisma/discussions/24407\n- That did work for me. thanks. (which smells like one ridicilous bug.).","metadata":{"transformedAt":"2026-08-18T18:33:14.816Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":171,"estimatedTokens":1219}}37{"id":"stack-75947475","source":"stackoverflow","questionId":75947475,"title":"Prisma: TypeError: Do not know how to serialize a BigInt","tags":["mysql","node.js","nestjs","prisma"],"text":"Title: Prisma: TypeError: Do not know how to serialize a BigInt\nTags: mysql, node.js, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fetch data from database and this is my prisma model:\n\n```\nmodel instant_reports {\n id BigInt @id @default(autoincrement()) @db.UnsignedBigInt\n created_at DateTime?\n updated_at DateTime?\n deleted_at DateTime?\n timestamp BigInt?\n client_id BigInt?\n uniq_users BigInt?\n}\n```\n\nSo when i fetch data like this\n\n```\nprismaService.instant_reports.findMany({\n skip: 0,\n take: 30,\n });\n```\n\nIt throws error\n\nTypeError: Do not know how to serialize a BigInt at JSON.stringify()\n\nAnd i don't even know how to deal with it, is there way to change data handler in `findMany` method?\n\nIf there is no rows in `instant_reports` so it gives me empty array without error, so the problem is in data with BigInt type\n\n========================================\n\nTop Answer:\n### This is the most simple and secure way!!!\n\n### Modifying the prototype is likely to cause problems somewhere.\n\nJust copy and paste the simple function below.\n\n```\nconst json = (param: any): any => {\n return JSON.stringify(\n param,\n (key, value) => (typeof value === \"bigint\" ? value.toString() : value) // return everything else unchanged\n );\n};\nexport default json;\n```\n\nAnd then you can use like this\n\n```\nimport json from \"../helper/json\";\n\nrouter.get(\"/\", async (req: Request, res: Response) => {\n const users = await prisma.user.findMany({\n take: 15,\n });\n res.status(200).send(json(users));\n});\n```\n\nThis is how it works:\n\nMaybe most of us just want to send those Prisma datas in JSON format using ExpressJS.\n\nWhether you are using the library or not, you will inevitably go through `JSON.stringify()` at some point in your code.\n\nUnfortunately, `JSON.stringify()` can't handle BigInt correctly.\n\nSo, we all must have to convert BigInt to String if you want to use it.\n\n### ※ To ExpressJS users\n\nDon't use `res.json()` method!\n\nIf you use, you will unintentionally wrap twice like below\n\n`JSON.stringify(JSON.stringify(something))`\n\n========================================\n\nCode:\n```text\nmodel instant_reports {\n  id         BigInt    @id @default(autoincrement()) @db.UnsignedBigInt\n  created_at DateTime?\n  updated_at DateTime?\n  deleted_at DateTime?\n  timestamp  BigInt?\n  client_id  BigInt?\n  uniq_users BigInt?\n}\n```\n\n```text\nprismaService.instant_reports.findMany({\n      skip: 0,\n      take: 30,\n    });\n```\n\n```text\nfindMany\n```\n\n```text\ninstant_reports\n```\n\n```js\nBigInt.prototype.toJSON = function () {\n  const int = Number.parseInt(this.toString());\n  return int ?? this.toString();\n};\n```\n\n```text\nfunction bigIntToString(value) {\n  const MAX_SAFE_INTEGER = 2 ** 53 - 1;\n  return value <= MAX_SAFE_INTEGER ? Number(value) : value.toString();\n}\n\nfunction serializeInstantReports(instantReports) {\n  return instantReports.map(report => {\n    const newReport = { ...report };\n    if (typeof report.id === 'bigint') newReport.id = bigIntToString(report.id);\n    // ...\n    // such convirtions for other BigInt fields\n    // ...\n    return newReport;\n  });\n}\n```\n\n```text\nserializeInstantReports\n```\n\n```text\nconst user = prisma.user.create({ data: { id: 1, name: \"user\"})\n```\n\n```text\nJSON.stringify({...user, id: user.id.toString()})\n```\n\n```text\nconst json = (param: any): any => {\n  return JSON.stringify(\n    param,\n    (key, value) => (typeof value === \"bigint\" ? value.toString() : value) // return everything else unchanged\n  );\n};\nexport default json;\n```\n\n```text\nimport json from \"../helper/json\";\n\nrouter.get(\"/\", async (req: Request, res: Response) => {\n  const users = await prisma.user.findMany({\n    take: 15,\n  });\n  res.status(200).send(json(users));\n});\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nJSON.stringify()\n```\n\n```text\nres.json()\n```\n\n```text\nJSON.stringify(JSON.stringify(something))\n```\n\n```text\nconst overrideJsonBigIntSerialization = (): void => {\n  const originalJSONStringify = JSON.stringify\n    \n  JSON.stringify = function (value: any, replacer, space: number): string {\n    const bigIntReplacer = (_key: string, value: any): any => {\n      if (typeof value === 'bigint') {\n        return parseInt(value.toString())\n      }\n      return value\n    }\n\n    const customReplacer = (key: string, value: any): any => {\n      if (Array.isArray(replacer) && !replacer.includes(key) && key !== '') {\n        return undefined\n      }\n\n      const modifiedValue = bigIntReplacer(key, value)\n\n      if (typeof replacer === 'function') {\n        return replacer(key, modifiedValue)\n      }\n    \n      return modifiedValue\n    }\n  \n    return originalJSONStringify(value, replacer != null ? customReplacer : bigIntReplacer, space)\n  }\n}\n```\n\n```text\noverrideJsonBigIntSerialization()\n```\n\n========================================\n\nComments:\n- Does this answer your question? TypeScript: serialize BigInt in JSON\n- Brilliant. Thank you!\n- For NestJS, this needs to be added in bootstrap function in main.ts before app.listen line\n- Also, this must be approved as accepted answer since it solves the problem. I have upvoted it. @bluepuper\n- For nuxtjs, this could be added as a plugin // plugins/bigint-json.js export default defineNuxtPlugin(() => { BigInt.prototype.toJSON = function () { const int = Number.parseInt(this.toString()); return int ?? this.toString(); }; });\n- Even better, use superjson to handle all sorts of unsupported datatypes in addition to BigInt","metadata":{"transformedAt":"2026-08-18T18:33:14.816Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":234,"estimatedTokens":1353}}38{"id":"stack-76978671","source":"stackoverflow","questionId":76978671,"title":"NestJS and Prisma, do we really need DTOs for validation when we could use Prisma Generated Type?","tags":["typescript","nestjs","prisma","dto","class-validator"],"text":"Title: NestJS and Prisma, do we really need DTOs for validation when we could use Prisma Generated Type?\nTags: typescript, nestjs, prisma, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI m building a NestJS project using Prisma ORM, and after some tutorial and check on the subject, I don't see (or seem to understand) the use of DTO here, when we could use the Prisma Generated Type\n\nIt's seems to be a duplication of what we already did in the Prisma Schema, and could lead to bad update later as we will have to update both the schema and the DTOs\n\nAfter some search on it I come to the solution to directly use the Prisma Generated Type (as UserCreateInput / UserGetPayload)\n\nhere is the code that I did :\n\nusers.interface.ts\n\n```\nimport { type Prisma } from \"@prisma-postgresql\";\n\n// select for query filtering\nexport const UsersSelect = {\n name: true,\n email: true,\n} satisfies Prisma.UsersSelect;\n// UsersGetPayload is autogenerated by prisma after migration\nexport type Users = Prisma.UsersGetPayload;\n```\n\nusers.service.ts\n\n```\nimport { Injectable } from \"@nestjs/common\";\n\n// prisma import\nimport { PrismaPostgresqlService } from \"../../prisma/services/prisma-postgresql.service\";\nimport { Users, UsersSelect } from \"../interfaces/user.interface\";\n\n@Injectable()\nexport class UserService {\n private prismaSQL;\n\n constructor(prismaSQL: PrismaPostgresqlService) {\n this.prismaSQL = prismaSQL;\n }\n\n async findAll(): Promise {\n return await this.prismaSQL.users.findMany({\n select: UsersSelect,\n });\n }\n}\n```\n\nwith this I can have my own type coming directly from prisma\n\nI don't know if it's indeed a good solution or not, maybe I m missing the point of DTOs here ?\n\nWhy would it be a good idea to still use DTOs in my case ? or is this a good solution ?\n\n========================================\n\nTop Answer:\nValentin, \n\nIMHO, DTOs are not always required. It depends on how you are organizing your app. If you are not interested in decoupling your code from the framework you are using, it sounds good to use the auto-generated types. As you said, it can bring more complexity than what you need. I would suggest starting that way, and as your app evolves it will show the necessity of creating DTOs or not.\n\n========================================\n\nCode:\n```js\nimport { type Prisma } from \"@prisma-postgresql\";\n\n// select for query filtering\nexport const UsersSelect = {\n    name: true,\n    email: true,\n} satisfies Prisma.UsersSelect;\n// UsersGetPayload is autogenerated by prisma after migration\nexport type Users = Prisma.UsersGetPayload<{ select: typeof UsersSelect }>;\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\n\n// prisma import\nimport { PrismaPostgresqlService } from \"../../prisma/services/prisma-postgresql.service\";\nimport { Users, UsersSelect } from \"../interfaces/user.interface\";\n\n@Injectable()\nexport class UserService {\n    private prismaSQL;\n\n    constructor(prismaSQL: PrismaPostgresqlService) {\n        this.prismaSQL = prismaSQL;\n    }\n\n    async findAll(): Promise<Users[]> {\n        return await this.prismaSQL.users.findMany({\n            select: UsersSelect,\n        });\n    }\n}\n```\n\n========================================\n\nComments:\n- That is the point of my question, I don't know why would I need it later, even if my app evolves, what are the need I could meet later ? As I said, everyone (even NestJS in their exemples) seems to be using DTOs at the start, so what I want to point is **Are we missing the power of prisma** ? Like is everyone using Dtos Cause they didn't find / look a way to directly use prisma to do it ? That is what I m trying to understand here, as you said, maybe later I will see the use of DTOs, but I want to find what could be this reason\n- scenario 1: You have a REST API that provides a GET for the user resource. The contract (data representation) that you have defined for the route has more information than you would have in a specific domain model. In the backend, you are gathering info from multiple models (user, address, payment, etc.) and then returning it to the client. In that case, I see the need for a DTO.\n- scenario 2: You have a REST API that provides POST, PATCH, and GET routes for user resource. For the POST DTO, you defined the contract with some fields being mandatory, such as name, email, and password. For the PATCH DTO you are not allowing changes on field email, then you will not have this field, and the name and password are optional. And, the GET DTO has more info than the POST and PATCH DTOs, for instance, it would contain the fields: id, name, email, password, createdAt, updatedAt. So, your GET DTO can be reused by the POST and PATCH to return the result to the client.\n- I hope that clarifies a bit for you :)\n- thanks for the example :) Taking everything you said, PRISMA type do handle and allow almost all the case EXCEPT one, the PUT/PATCH case With the generated type you can't specifically say what is not allowed or not to be updated, so you have to manually extract which data should be updated and the request will not be rejected if it's pass data that should not be allowed to be updated This do not affect documentation as we can specify allowed params with NestJS decorators And this should soon be covered by the Prisma team, as this is one of the most requested feature\n- github.com/prisma/prisma/issues/3401 So when this will be added to prisma, there should be a new generated type for only allowed property to be updated, and all the case should be covered That aside, when this will be added to PRISMA, all the case where DTOs could be used would be gone right ?\n- For your case case, yes. Although, as I said, you are being tight coupling to the framework. As you are using its auto-generated types all over your app. And, there is nothing wrong with going that way, it is just a matter of trade-offs that we always have to make when building software.\n- Yes, in the end if we think about the day we might want to change the framework we use it might be the best to go with DTO, also they are some tool that exist to update our DTO using the prisma schema\n- In the end it might be best to use DTOs, allowing swagger to work properly and decoupling the solution from the framework\n- the DTO generator that you've linked is a fork of a fork of a fork. Now, I don't know the details, but i figured that the original repo would be preferable to use: github.com/vegardit/prisma-generator-nestjs-dto\n- indeed, really weird I didn't see that sooner I will update my answer to this link","metadata":{"transformedAt":"2026-08-18T18:33:14.816Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":117,"estimatedTokens":1633}}39{"id":"stack-63684133","source":"stackoverflow","questionId":63684133,"title":"prisma can't connect to postgresql","tags":["postgresql","prisma"],"text":"Title: prisma can't connect to postgresql\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI've tried to connect Prisma with postgreSQL several times.\nprisma show this error message : \"Error: undefined: invalid port number in \"postgresql://postgres:password@localhost:5432/linker\")\".\n\n-error\nhttps://i.sstatic.net/dU9Z7.jpg\n\n-prisma/.env\n\n```\nDATABASE_URL=postgresql://postgres:password@localhost:5432/linker\n```\n\n-schema.prisma\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n```\n\nSo, first, I checked the port number to see if it was right and 5432 is right because I use the default port number. I also checked the postgresql.conf file, which is set to \"listen_address=\"*\"\" , \"port=5432\".\n\nhttps://i.sstatic.net/JQ0c9.jpg\n\nAnd I went into pgAdmin4 and saw server's properties. the port number was 5432 as shown below image, and the username was set \"postgres\".\n\nhttps://i.sstatic.net/V5ufa.jpg\n\nI don't know why prisma can't connect\n\nDid i something missed?\n\n========================================\n\nTop Answer:\nFor anyone running into this, see the comments above on the answer!\n\nRemoving symbols from the db password (hosted on AWS RDS) fixed the problem for me.\n\n========================================\n\nCode:\n```text\nDATABASE_URL=postgresql://postgres:password@localhost:5432/linker\n```\n\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n```text\nDATABASE_URL\n```\n\n```text\n.env\n```\n\n```text\n@\n```\n\n```text\n%40\n```\n\n```text\n#\n```\n\n```text\n%23\n```\n\n```text\n!\n```\n\n```text\n%21\n```\n\n```text\n#\n```\n\n```text\n%23\n```\n\n```text\n$\n```\n\n```text\n%24\n```\n\n```text\n%\n```\n\n```text\n%25\n```\n\n```text\n&\n```\n\n```text\n%26\n```\n\n```text\n'\n```\n\n```text\n%27\n```\n\n```text\n(\n```\n\n```text\n%28\n```\n\n```text\n)\n```\n\n```text\n%29\n```\n\n```text\n*\n```\n\n```text\n%2A\n```\n\n```text\n+\n```\n\n```text\n%2B\n```\n\n```text\n,\n```\n\n```text\n%2C\n```\n\n```text\n/\n```\n\n```text\n%2F\n```\n\n```text\n:\n```\n\n```text\n%3A\n```\n\n```text\n;\n```\n\n```text\n%3B\n```\n\n```text\n=\n```\n\n```text\n%3D\n```\n\n```text\n?\n```\n\n```text\n%3F\n```\n\n```text\n@\n```\n\n```text\n%40\n```\n\n```text\n[\n```\n\n```text\n%5B\n```\n\n```text\n]\n```\n\n```text\n%5D\n```\n\n```text\nnewline\n```\n\n```text\n%0A\n```\n\n```text\n%0D\n```\n\n```text\n%0D%0A\n```\n\n```text\nspace\n```\n\n```text\n%20\n```\n\n```text\n\"\n```\n\n```text\n%22\n```\n\n```text\n%\n```\n\n```text\n%25\n```\n\n```text\n-\n```\n\n```text\n%2D\n```\n\n```text\n.\n```\n\n```text\n%2E\n```\n\n```text\n<\n```\n\n```text\n%3C\n```\n\n```text\n>\n```\n\n```text\n%3E\n```\n\n```text\n\\\n```\n\n```text\n%5C\n```\n\n```text\n^\n```\n\n```text\n%5E\n```\n\n```text\n_\n```\n\n```text\n%5F\n```\n\n```text\n`\n```\n\n```text\n{\n```\n\n```text\n%7B\n```\n\n```text\n|\n```\n\n```text\n%7C\n```\n\n```text\n}\n```\n\n```text\n%7D\n```\n\n```text\n~\n```\n\n```text\n%7E\n```\n\n```text\n£\n```\n\n```text\n%C2%A3\n```\n\n```text\n円\n```\n\n```text\n%E5%86%86\n```\n\n```bash\nnode\n```\n\n```js\nnew URLSearchParams({pass: \"YOUR_PASSWORD_WITH_SPECIAL_CHARACTERS\"}).toString().substring(5)\n```\n\n```text\n'YOUR_PASSWORD_URL_ENCODED'\n```\n\n```text\nencodeURIComponent('your-password')\n```\n\n```text\nCtrl + Shift + P\n```\n\n========================================\n\nComments:\n- Where is \"Prisma\" running. On the same machine like the database server or in a Docker container ...?\n- @madflow same machine, i'm using windows 10, visual studio code\n- on Supabase, too.\n- Thanks! this worked, I replaced all the special characters with the above Encodings and it worked\n- Any library that does this?\n- @Nobody, Not that I'm aware of but you can easily write your own by scanning the strings and replacing them with the corresponding characters.\n- To be clear, you would encode EVERY special character in this string? `mysql:&#47;&#47;USER:PA$$WORD@HOST:PORT&#47;DATABASE?connection_limit=5` - the colon and backslashes after the word \"mysql?\" The colons separating USER and PA$$WORD? The $ in the password? The @ separating PA$$WORD and HOST? The ? for the query parameter? The = sign? I have tried some and all and cannot get it to work\n- @user210757, only in your username and password. In your case only `$$`. That will result in `mysql:&#47;&#47;USER:PA%24%24WORD@HOST:PORT&#47;DATABASE?connection_limi&zwnj;&#8203;t=5`. I hope you have also provided the actual values for HOST, PORT and DATABASE in your real url and this just an example string.\n- Wow, this helped me. So bizarre. I needed to replace characters like you instructed but only in my `SHADOW_DATABASE_URL` prisma.io/docs/concepts/components/prisma-migrate/&hellip; and not in my `DATABASE_URL`. Weird.\n- This happened for me again. I'm using Prisma and MySql. I only needed to urlEncode the `SHADOW_DATABASE_URL`'s password. Underscores in the username were fine unencoded (same with DB name).","metadata":{"transformedAt":"2026-08-18T18:33:14.816Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":88,"totalLines":416,"estimatedTokens":1158}}40{"id":"stack-68702024","source":"stackoverflow","questionId":68702024,"title":"Why \"null\" can't be the default value of a nullable column?","tags":["orm","prisma"],"text":"Title: Why \"null\" can't be the default value of a nullable column?\nTags: orm, prisma\nSource: Stack Overflow\n\nQuestion:\nConsider this schema:\n\n```\nmodel Comment {\n id Int @id @default(autoincrement())\n reply Comment? @relation(fields: [replyId], references: [id], onDelete: SetNull)\n replyId Int? @default(null)\n comment String\n}\n```\n\nHere both `reply` and `replyId` are nullable. When I migrate I get this error:\n\n```\nerror: Error parsing attribute \"@default\": Expected a numeric value, but received literal value \"Null\".\n --> schema.prisma:70\n |\n69 | reply Comment? @relation(fields: [replyId], references: [id], onDelete: SetNull)\n70 | replyId Int? @default(null)\n |\n```\n\nWhy?\n\n========================================\n\nCode:\n```text\nmodel Comment {\n  id        Int        @id @default(autoincrement())\n  reply     Comment?   @relation(fields: [replyId], references: [id], onDelete: SetNull)\n  replyId   Int?       @default(null)\n  comment   String\n}\n```\n\n```text\nerror: Error parsing attribute \"@default\": Expected a numeric value, but received literal value \"Null\".\n  -->  schema.prisma:70\n   |\n69 |   reply     Comment? @relation(fields: [replyId], references: [id], onDelete: SetNull)\n70 |   replyId   Int?     @default(null)\n   |\n```\n\n```text\nreply\n```\n\n```text\nreplyId\n```\n\n```text\nComment\n```\n\n```text\nreplyId\n```\n\n```text\nreplyId\n```\n\n```text\n@default(null)\n```\n\n========================================\n\nComments:\n- Thank you. you are the only person that answers my Prisma questions:). I thought that because replyId is an integer, its default value is 0.\n- Optional fields, regardless of the type are nullable and defaults to null. And happy to help :D\n- yep the \"Int?\" actually means, set to null if nothing is provided.\n- There is however a use case where someone would want to have NULL as default rather than undefine. For instance, PostgreSQL guarantees 'uniqueness' for NULL fields but not for undefined.\n- I have same problem. I this answer to used `DateTime?` optional type data and work to create default `NULL` :D\n- this is not true for mongodb\n- I just let it like this `deletedAt DateTime?`, without any default, it is working in localdb","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":84,"estimatedTokens":541}}41{"id":"stack-65384818","source":"stackoverflow","questionId":65384818,"title":"Error when migrating models to database Prisma","tags":["postgresql","heroku","prisma"],"text":"Title: Error when migrating models to database Prisma\nTags: postgresql, heroku, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm starting a project where I have to learn a new technology and I chose to build a full-stack app with Prisma and Next.js. I'm using both for the first time. I've built front-end apps w/ React.js and feel confident about using Next. However, I'm having a hard time getting started with Prisma.\nI'm following Prisma's 'Start from Scratch' instructions and I'm stuck on the step **\"To map your data model to the database schema, you need to use the prisma migrate CLI commands: \"** and I run the command:\n`npx prisma migrate dev --name init --preview-feature`\nI get the error:\n\n```\nP3014\nPrisma Migrate could not create the shadow database. Please make sure the database user has permission to create databases. More info: https://pris.ly/d/migrate-shadow. Original error: \nDatabase error: Error querying the database: db error: ERROR: permission denied to create database\n```\n\nMy database is postgresQL and it's hosted on heroku. My DATABASE_URL is copied/pasted from the configs on heroku.\n\nHere are my .json dependencies:\n\n```\n\"name\": \"photo_album\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"scripts\": {\n \"prisma\": \"prisma\",\n \"dev\": \"next dev\",\n \"build\": \"next build\",\n \"start\": \"next start\"\n },\n \"dependencies\": {\n \"@prisma/client\": \"^2.13.1\",\n \"next\": \"10.0.3\",\n \"react\": \"17.0.1\",\n \"react-dom\": \"17.0.1\"\n },\n \"devDependencies\": {\n \"@prisma/cli\": \"^2.13.1\"\n }\n}\n```\n\nI tried **Introspect**. But, my DB currently has no tables and that threw an error. I tried **npx prisma migrate save -experimental** b/c of a build I saw on youtube. I tried **npm install @prisma/cli --save-dev** b/c that worked for the same problem posted here on stackoverflow.\nAnother solution said to use Docker. I haven't tried that yet.\n\n========================================\n\nTop Answer:\nAccording to nikolasburk you can also run `prisma db push` instead of the `prisma migrate dev` command, just run:\n\n```\nnpx prisma db push --preview-feature\n```\n\n========================================\n\nCode:\n```text\nP3014\nPrisma Migrate could not create the shadow database. Please make sure the database user has permission to create databases.  More info: https://pris.ly/d/migrate-shadow. Original error: \nDatabase error: Error querying the database: db error: ERROR: permission denied to create database\n```\n\n```text\n\"name\": \"photo_album\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"prisma\": \"prisma\",\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"start\": \"next start\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"^2.13.1\",\n    \"next\": \"10.0.3\",\n    \"react\": \"17.0.1\",\n    \"react-dom\": \"17.0.1\"\n  },\n  \"devDependencies\": {\n    \"@prisma/cli\": \"^2.13.1\"\n  }\n}\n```\n\n```text\nnpx prisma migrate dev --name init --preview-feature\n```\n\n```text\nnpx prisma db push --preview-feature\n```\n\n```text\nprisma db push\n```\n\n```text\nprisma migrate dev\n```\n\n```text\ndatasource db {\n  provider          = \"postgresql\"\n  url               = env(\"DATABASE_URL\")\n  shadowDatabaseUrl = env(\"SHADOW_DATABASE_URL\")\n}\n```\n\n```text\nALTER USER admin CREATEDB;\n```\n\n```text\nadmin\n```\n\n```text\nprisma/migration\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpm start\n```\n\n========================================\n\nComments:\n- Thank you for posting this answer! I'm pretty sure it worked. I say pretty sure because I don't see the tables/models on my heroku DB. But, I do see the migration on there! That's a step in the right direction\n- Apparently this is still an issue in 2023. Not using Heroku, but cockroachlabs db.\n- just put prisma.config.ts at the root of the project and it worked\n- Although it solves the problem temporarily but doesn't solve the permission issue. So as you try to add records through `prisma studio` it won't allow you due to access issues\n- Thank you for this solution. This is perfect for those DB who don't have admin access. (e.g. Shared Host). You simply create two DB schema and then it all good to go :D\n- This is the best answer for me.\n- This is the one. Should be the accepted answer\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":144,"estimatedTokens":1111}}42{"id":"stack-70228893","source":"stackoverflow","questionId":70228893,"title":"Testing a NestJS Service that uses Prisma without actually accessing the database","tags":["jestjs","nestjs","prisma"],"text":"Title: Testing a NestJS Service that uses Prisma without actually accessing the database\nTags: jestjs, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nMost examples I've seen of how to test a Prisma-injected NestJS Service (e.g. `prisma-sample` in `testing-nestjs`) are for \"end to end\" testing. They actually access the database, performing actual queries and then rolling back the results if necessary.\n\nFor my current needs, I want to implement lower-level \"integration\" testing.\n\nAs part of this, I want to remove Prisma from the equation. I want the focus to be on my service's functionality instead of the state of data within the database and Prisma's ability to return it.\n\nOne big win of this approach is that it obviates the need to craft \"setup\" queries and \"teardown\"/reset operations for specific tests. Instead, I'd like to simply manually specify what we would expect Prisma to return.\n\nIn an environment consisting of NestJS, Prisma, and Jest, how should I accomplish this?\n\nUPDATE: The author of the testing-nestjs project pointed out in the comments that the project does have an example of database mocking. It looks nice! Others may still be interested in checking out the Gist that I've linked to as it includes some other useful functionality.\n\n========================================\n\nTop Answer:\nTo get a reference to your service's prisma instance, use:\n\n```\nprisma = module.get(PrismaService)\n```\n\nThen, assuming your function calls `prisma.name.findMany()`, you can use `jest.fn().mockReturnValueOnce()` to mock (manually specify) Prisma's next return value:\n\n```\nprisma.name.findMany = jest.fn().mockReturnValueOnce([\n { id: 0, name: 'developer' },\n { id: 10, name: 'architect' },\n { id: 13, name: 'dog walker' }\n]);\n```\n\n(Of course, you would change `prisma.name.findMany` in the code above to match whatever function you're calling.)\n\nThen, call the function on your Service that you're testing. For example:\n\n```\nexpect(await service.getFirstJob(\"steve\")).toBe('developer');\n```\n\nThat's it! A full code example can be found here.\n\n========================================\n\nCode:\n```text\nprisma-sample\n```\n\n```text\ntesting-nestjs\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PrismaClient } from '@prisma/client'\nimport { mockDeep, DeepMockProxy } from 'jest-mock-extended'\n    \ndescribe('UserService', () => {\n  let service: UserService;\n  let prisma: DeepMockProxy<PrismaClient>;\n    \n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      providers: [UserService, PrismaService],\n    })\n      .overrideProvider(PrismaService)\n      .useValue(mockDeep<PrismaClient>())\n      .compile();\n    \n    service = module.get(UserService);\n    prisma = module.get(PrismaService);\n  });\n    \n\n  it('returns users', () => {\n    const testUsers = [];\n\n    prisma.user.findMany.mockResolvedValueOnce(testUsers);\n\n    expect(service.findAll()).resolves.toBe(testUsers);\n  });\n});\n```\n\n```text\njest-mock-extended\n```\n\n```text\nPrismaService\n```\n\n```js\nprisma = module.get<PrismaService>(PrismaService)\n```\n\n```js\nprisma.name.findMany = jest.fn().mockReturnValueOnce([\n    { id: 0, name: 'developer' },\n    { id: 10, name: 'architect' },\n    { id: 13, name: 'dog walker' }\n]);\n```\n\n```js\nexpect(await service.getFirstJob(\"steve\")).toBe('developer');\n```\n\n```text\nprisma.name.findMany()\n```\n\n```text\njest.fn().mockReturnValueOnce()\n```\n\n```text\nprisma.name.findMany\n```\n\n```js\nimport { Controller, Get } from '@nestjs/common';\nimport { DbService } from 'src/db/db.service';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(\n    private readonly appService: AppService,\n    private readonly prisma: DbService,\n  ) {}\n\n  @Get()\n  async getHello(): Promise<string> {\n    const result = await this.prisma.user.findMany();\n\n    console.log('result', result);\n\n    return this.appService.getHello();\n  }\n}\n```\n\n```js\ndescribe('AppController', () => {\n  let appController: AppController;\n\n  const mockPrisma = {\n    user: { findMany: () => Promise.resolve([]) },\n  };\n\n  beforeEach(async () => {\n    const app: TestingModule = await Test.createTestingModule({\n      controllers: [AppController],\n      providers: [AppService, DbService],\n    })\n      .overrideProvider(DbService)\n      .useValue(mockPrisma)\n      .compile();\n\n    appController = app.get<AppController>(AppController);\n  });\n\n  describe('root', () => {\n    it('should return \"Hello World!\"', () => {\n      expect(appController.getHello()).resolves.toBe('Hello World!');\n    });\n  });\n});\n```\n\n```js\n@Injectable()\nexport class DbService extends PrismaClient implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });\n  }\n}\n```\n\n```text\nDbService\n```\n\n```text\n'DbService'\n```\n\n========================================\n\nComments:\n- As you can see, I've added my own answer already. I'm curious what other approaches others prefer.\n- By the way, that same `testing-nestjs` repo you linked, it has unit tests for prisma where the database *is* mocked (source, I'm the author)\n- @JayMcDoniel I thought you’d see this! 👋 Can you a link? All I remember seeing were tests that seemed to be perform actual queries on the DB. Maybe I just misunderstood.\n- I was on mobile and didn't see the link - I'll check it out!\n- Ahhhh I see now - I thought the repo only had e2e tests. This is great; thanks, Jay!\n- In your gists, do we need to extend toHaveBeenCalledWithObjectMatchingHash method always?\n- Hi, @SangbeomHan - I'll respond on GitHub.\n- This doesn't work for me. I get the error \"Cannot read properties of undefined (reading 'name')\" Where name ofcourse is the function I use\n- @Sytham That means that `prisma` is `undefined` for you. Try to figure out what you need to use instead.\n- You'll get `Cannot read properties of undefined (reading 'name')` if the Prisma is set to auto-connect on app boot (and if there is no DB, you have then used jest.mock). Set it to lazy connect, or use David F's approach.\n- I'd prefer this way of doing it since it's the one recommended by the official docs. Thank you for providing the Nest example!\n- Should be the recommended answer, this is the cleanest solution\n- Sure - updated this answer to be the accepted one. (feel free to disagree, anyone!)","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":215,"estimatedTokens":1609}}43{"id":"stack-56995111","source":"stackoverflow","questionId":56995111,"title":"how to get the total matched record count in prisma-binding npm","tags":["node.js","graphql","prisma","prisma-binding"],"text":"Title: how to get the total matched record count in prisma-binding npm\nTags: node.js, graphql, prisma, prisma-binding\nSource: Stack Overflow\n\nQuestion:\nI have been using prisma-binding npm, I don't know how to get the total matched count of the query in order to perform pagination.\n\nI'm using below code to pull record which working fine. Now i want total number of records.\n\n```\nconst users = await prisma.query.users(null,`{id, name}`)\n```\n\nNote: By default prisma returns maximum of 3000 records only, but have 9000 records.\n\n========================================\n\nCode:\n```text\nconst users = await prisma.query.users(null,`{id, name}`)\n```\n\n```text\nconst count = await prisma.query.usersConnection({\n  where: {\n    // whatever your filter parameters are\n  }\n}, `{ aggregate { count } }`)\n```\n\n```text\nusersConnection\n```\n\n========================================\n\nComments:\n- Glad it works. Please mark as correct if you're happy with it.","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":38,"estimatedTokens":237}}44{"id":"stack-74328100","source":"stackoverflow","questionId":74328100,"title":"Prisma find many and count in one request","tags":["javascript","backend","prisma"],"text":"Title: Prisma find many and count in one request\nTags: javascript, backend, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a pagination in my category service, and I have to return obj with *total count of categories* and *data*\n\nBut there's can be some parameters. As example, I should return categories that was created by certain user:\n\n```\nasync findAll(\n { onlyParents }: ParamsCategoryDto,\n user: ITokenPayload | undefined,\n): Promise {\n const categories = await this.prisma.category.findMany({\n where: {\n user_id: user?.id,\n },\n });\n\n return {\n pagination: {\n total: this.prisma.category.count({\n where: { // I should duplicate *where* in both query. Which is not very nice. Is there any option to do it in one request.\n\nP.S. I can make some var for where, but in this way I lose typification, which I also don't like.\n\n========================================\n\nTop Answer:\nJust in addition to approved answer\n\nWhen you make some nested queries from another tables inside `findMany`, you should use `satisfies` instead strict type declaration, to make it exists in result type.\n\nFor example, instead\n\n```\nconst query: Prisma.categoriesFindManyArgs = {\n where: {\n user_id: userId,\n }\n};\n```\n\nyou should write\n\n```\nconst query = {\n where: {\n user_id: userId,\n }\n} satisfies Prisma.categoriesFindManyArgs;\n```\n\nNow, Typescript will know and use exactly your type definition instead predefined and allow to you use all features of types inference\n\n========================================\n\nCode:\n```js\nasync findAll(\n    { onlyParents }: ParamsCategoryDto,\n    user: ITokenPayload | undefined,\n): Promise<IFilterRes> {\n    const categories = await this.prisma.category.findMany({\n      where: {\n        user_id: user?.id,\n      },\n    });\n\n    return {\n      pagination: {\n        total: this.prisma.category.count({\n          where: { // <- duplicate\n          user_id: user?.id,\n        },\n      }),\n    },\n    data: categories,\n  };\n}\n```\n\n```ts\nimport { Prisma } from '@prisma/client';\nimport { PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n\nconst findAll = async (userId: String) => {\n  const query: Prisma.categoriesFindManyArgs = {\n    where: {\n      user_id: userId,\n    }\n  };\n  const [categories, count] = await prisma.$transaction([\n    prisma.categories.findMany(query),\n    prisma.categories.count({ where: query.where })\n  ]);\n\n  return {\n    pagination: {\n      total: count\n    },\n    data: categories\n  };\n};\n```\n\n```text\nconst query: Prisma.categoriesFindManyArgs = {\n    where: {\n      user_id: userId,\n    }\n};\n```\n\n```text\nconst query = {\n    where: {\n      user_id: userId,\n    }\n} satisfies Prisma.categoriesFindManyArgs;\n```\n\n```text\nfindMany\n```\n\n```text\nsatisfies\n```\n\n```text\nawait this.prisma.category.count({\n  where: {\n    user_id: user?.id,\n  },\n})\n```\n\n========================================\n\nComments:\n- Oh, that's good alternative. It's very sad that prisma doesn't have such from a box. But I think you offer a really good way\n- But this would still be making two separate database requests right?\n- Not only does this make 2 separate database requests, but because there is only one DB connection per prisma server, it actually doesn't help increase the speed. If either of these is a long running request, both calls will freeze everyone else trying to access data on that server. But I agree the code does look cleaner.","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":146,"estimatedTokens":847}}45{"id":"stack-54343288","source":"stackoverflow","questionId":54343288,"title":"'prisma' is not recognized as an internal or external command, operable program or batch file","tags":["reactjs","npm","prisma","prisma-graphql"],"text":"Title: 'prisma' is not recognized as an internal or external command, operable program or batch file\nTags: reactjs, npm, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nHi everyone I am getting this error **\"'prisma' is not recognized as an internal or external command, operable program or batch file.\"** while running prisma login command in cmd I have installed the prisma globally with **npm install -g prisma** any solution will be appreciated.\n\nhttps://i.sstatic.net/Op7j7.png\n\n========================================\n\nTop Answer:\nInstall it globally with; `npm i -g prisma`\n\n========================================\n\nCode:\n```text\nprisma\n```\n\n```text\nprisma\n```\n\n```text\nnpm i -g prisma\n```\n\n```text\nnpm i prisma @prisma/client\n- or -\npnpm i prisma @prisma/client\n- or -\nyarn add prisma @prisma/client\n```\n\n```text\nnpx prisma generate\n- or -\npnpm dlx prisma generate\n- or -\nyarn prisma\n```\n\n```text\nprisma\n```\n\n```text\nprisma generate\n```\n\n```text\nnode_modules\n```\n\n```text\nbunx prisma\n```\n\n```text\nnpm\n```\n\n```text\nbun\n```\n\n```text\nnpx\n```\n\n```text\nbunx\n```\n\n```text\nbun x\n```\n\n```text\nbun prisma init\n```\n\n```text\nprisma init\n```\n\n========================================\n\nComments:\n- This should be the accepted answer; simple clear & is the resolution.\n- This is just a workaround. Author said he installed prisma globally. Sometimes you don't want to or simply cannot install modules as global. Also the accepted answer points to the real problem there: PATH in Windows (Author uses windows environment). 'npx prisma generate' is simpler and cleaner. It will generate the executable in the local dev environment.\n- This works for me\n- Keep in mind that the question didn't ask about Bun or bunx, but specifically about Node/npm. If we simply posted new Bun answers on all of the old Node questions, then we'd have thousands of new answers that aren't needed. If you had a similar issue with Bun, then post a new question about it and self-answer. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":96,"estimatedTokens":494}}46{"id":"stack-69679956","source":"stackoverflow","questionId":69679956,"title":"NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records?","tags":["node.js","typescript","postgresql","nestjs","prisma"],"text":"Title: NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records?\nTags: node.js, typescript, postgresql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fetch data records from a Postgres database in NestJS (Node.JS environment).\n\nI'm using Prisma as my Object Relational Mapper (ORM) in TypeScript.\n\nI'm having trouble choosing which query to use when fetching 'ADMIN' user records.\n\nSomeone please explain the difference between using 'select' versus using 'include' when fetching data records (I'm a Prisma beginner - please keep it simple).\n\nThanks in advance!\n\nThe code looks like below:\n\nUsing include:\n\n```\nconst users = await prisma.user.findMany({\n where: {\n role: 'ADMIN',\n },\n include: {\n posts: true,\n },\n})\n```\n\nUsing select:\n\n```\nconst users = await prisma.user.findMany({\n where: {\n role: 'ADMIN',\n },\n select: {\n posts: true,\n },\n})\n```\n\n========================================\n\nCode:\n```js\nconst users = await prisma.user.findMany({\n  where: {\n    role: 'ADMIN',\n  },\n  include: {\n    posts: true,\n  },\n})\n```\n\n```js\nconst users = await prisma.user.findMany({\n  where: {\n    role: 'ADMIN',\n  },\n  select: {\n    posts: true,\n  },\n})\n```\n\n```text\nconst getUser: object | null = await prisma.user.findUnique({\n  where: {\n    id: 22,\n  },\n  select: {\n    email: true,\n    name: true,\n  },\n})\n\n// Result\n{\n  name: \"Alice\",\n  email: \"alice@prisma.io\",\n}\n```\n\n```text\nconst users = await prisma.user.findMany({\n  select: {\n    name: true,\n    posts: {\n      select: {\n        title: true,\n      },\n    },\n  },\n})\n```\n\n```text\nconst getPosts = await prisma.post.findMany({\n  where: {\n    title: {\n      contains: 'cookies',\n    },\n  },\n  include: {\n    author: true, // Return all fields\n  },\n})\n\n// Result:\n;[\n  {\n    id: 17,\n    title: 'How to make cookies',\n    published: true,\n    authorId: 16,\n    comments: null,\n    views: 0,\n    likes: 0,\n    author: {\n      id: 16,\n      name: null,\n      email: 'orla@prisma.io',\n      profileViews: 0,\n      role: 'USER',\n      coinflips: [],\n    },\n  },\n  {\n    id: 21,\n    title: 'How to make cookies',\n    published: true,\n    authorId: 19,\n    comments: null,\n    views: 0,\n    likes: 0,\n    author: {\n      id: 19,\n      name: null,\n      email: 'emma@prisma.io',\n      profileViews: 0,\n      role: 'USER',\n      coinflips: [],\n    },\n  },\n]\n```\n\n```text\nconst users = await prisma.user.findMany({\n  // Returns all user fields\n  include: {\n    posts: {\n      select: {\n        title: true,\n      },\n    },\n  },\n})\n```\n\n========================================\n\nComments:\n- To be more clear, `include: {author: true}` includes all fields from the parent table AND the author table, whereas `select: {author: true}` returns ONLY fields from the `author` table.\n- Also note that `include: {author: false}` or `include: {author: 42}` also returns `author`s, it just check if the field is in `include` or not, but not it's value true or false.\n- Is there a performance difference or any difference at all between a nested select and a select within include? `select: { posts: { select: { title: true } }` vs `include: { posts: { select: { title: true } } }`","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":169,"estimatedTokens":788}}47{"id":"stack-68105010","source":"stackoverflow","questionId":68105010,"title":"Make a change to the database with Prisma.js without having to reset the whole thing","tags":["node.js","prisma","prisma2"],"text":"Title: Make a change to the database with Prisma.js without having to reset the whole thing\nTags: node.js, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nHow can make a change to the database with `Prisma.js` without having to reset the whole thing?\n\nif I have used this command\n\n```\nnpx prisma migrate dev --name role-makeOptional-NormalizedName\n```\n\nI will lose all of the data in my database but I don't lose my data.\n\nIn my case I wanted to change `String` to `String?` in `schema.prisma` file\n\n```\nNormalizedName String? @unique @db.VarChar(64)\n```\n\nIs there a proper command to avoid losing the data?\n\n========================================\n\nTop Answer:\nIn a development environment, Prisma Migrate sometimes prompts you to reset the database. Resetting drops and recreates the database, which results in data loss. The database is reset when:\n\n- You call `prisma migrate reset` explicitly\n\n- You call `prisma migrate dev` and Prisma Migrate detects drift in the database or a migration history conflict\n\nI'm not sure why Prisma thinks that your change is breaking, but there is probably no other way to make schema change without data loss.\n\nTo recreate your database data consider using seeding script\n\nIf you are prototyping, consider using the `db push` command, although it will still result in data reset if Prisma considers that the change is breaking.\n\n========================================\n\nCode:\n```text\nnpx prisma migrate dev --name role-makeOptional-NormalizedName\n```\n\n```text\nNormalizedName  String?            @unique @db.VarChar(64)\n```\n\n```text\nPrisma.js\n```\n\n```text\nString\n```\n\n```text\nString?\n```\n\n```text\nschema.prisma\n```\n\n```text\nNormalizedName  String            @unique @db.VarChar(64)\nNormalizedName  String?            @unique @db.VarChar(64)\n```\n\n```text\n$ npx prisma migrate dev --name migration-name --create-only\n```\n\n```text\nALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL;\n```\n\n```text\nALTER TABLE myTable ALTER COLUMN myColumn DROP NOT NULL;\n```\n\n```text\n$ npx prisma migrate dev\n```\n\n```text\nprisma migrate reset\n```\n\n```text\nprisma migrate dev\n```\n\n```text\ndb push\n```\n\n```text\n_prisma_migrations\n```\n\n```text\nnpx prisma migrate resolve --applied MIGRATION_NAME\n```\n\n```text\nprisma migrate deploy\n```\n\n========================================\n\nComments:\n- If you create your database with `db push` or for some other reason have no migrations table in your db then prisma will want to reset it every time.\n- **NOTE:** `--create-only` doesn't prevent data loss when Prisma detects a drift. It **\"should\"** *(at least the name implies that it \"should\")* prevent data loss but doesn't; in my experience it drops all tables except `_prisma_migrations` and then just doesn't re-create the tables. 🤔 Not sure why Prisma prioritizes complete data loss.\n- This doesn't work for me. Again prisma warns me that data will be lost.\n- data will still be lost\n- Why did you approved this answer? This isn't working.\n- You can run **npx prisma db push** instead of running the migration so this will just push the schema updates without making you loose data.","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":119,"estimatedTokens":777}}48{"id":"stack-70745094","source":"stackoverflow","questionId":70745094,"title":"How to deploy to Vercel with dynamically generated package from Prisma","tags":["javascript","npm","next.js","prisma","vercel"],"text":"Title: How to deploy to Vercel with dynamically generated package from Prisma\nTags: javascript, npm, next.js, prisma, vercel\nSource: Stack Overflow\n\nQuestion:\nI'm using Prisma and Vercel. Prisma dynamically generates the Prisma client, but Vercel caches the old client and doesn't rebuild it unless I log in to Vercel and click \"redeploy\" which forces it to reinstall all the packages.\n\nIs there any way to force this one package to just rebuild every time I push to GitHub, so that Vercel won't use the cached version? I noticed that if I change the package version, it will rebuild, but that's a pretty big hack. Is there some way to flag it to rebuild every time?\n\n```\n\"@prisma/client\": \"3.8.0\" // some special flag to prevent this from getting cached?\n```\n\n========================================\n\nTop Answer:\n```\n\"scripts\" {\n \"postinstall\": \"prisma generate\"\n }\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n```\n\nhttps://www.prisma.io/docs/orm/prisma-client/deployment/serverless/deploy-to-vercel\n\n========================================\n\nCode:\n```text\n\"@prisma/client\": \"3.8.0\" // some special flag to prevent this from getting cached?\n```\n\n```text\n// package.json scripts section\n\"vercel-build\": \"prisma generate && prisma migrate deploy && next build\",\n```\n\n```text\n\"scripts\" {\n    \"postinstall\": \"prisma generate\"\n  }\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n```\n\n========================================\n\nComments:\n- \"postinstall\": \"prisma generate && prisma migrate deploy\" is another option\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":55,"estimatedTokens":437}}49{"id":"stack-68810116","source":"stackoverflow","questionId":68810116,"title":"check if record exists using prisma graphql apollo","tags":["graphql","apollo-server","prisma"],"text":"Title: check if record exists using prisma graphql apollo\nTags: graphql, apollo-server, prisma\nSource: Stack Overflow\n\nQuestion:\ntrying to check if a record exists in a table in Postgres using Prisma, but seems like I can only query the id field, but not any other fields like `name` and `location`, which gives a compiler error\n\nmodel `schema.prisma`\n\n```\nmodel place {\n id Int @id @default(dbgenerated(\"nextval('place_id_seq'::regclass)\"))\n name String\n location String @unique\n}\n```\n\ngenerated type\n\n```\nexport type Place = {\n __typename?: 'Place';\n name?: Maybe;\n location?: Maybe;\n\n};\n```\n\nQuery resolver\n\n```\nlet findPlace = await prisma.place.findUnique(\n {\n where: {\n name: \"abc\"\n }\n }\n)\n```\n\nerror\n\n```\nType '{ name: string; }' is not assignable to type 'placeWhereUniqueInput'.\n Object literal may only specify known properties, and 'name' does not exist in type 'placeWhereUniqueInput'.ts(2322)\nindex.d.ts(1361, 5): The expected type comes from property 'where' which is declared here on type '{ select?: placeSelect | null | undefined; include?: placeInclude | null | undefined; rejectOnNotFound?: RejectOnNotFound | undefined; where: placeWhereUniqueInput; }'\n```\n\nwhat's missing here to make this work?\n\n========================================\n\nTop Answer:\n`findUnique` only works for unique fields. You shouldn't use `count` either as it unnecessarily goes through the whole table.\n\nThe better approach is to use `findFirst`, which is basically a `LIMIT 1` on the database, so the database can stop searching for more results after the first hit.\n\n```\nconst exists = !!await prisma.place.findFirst(\n {\n where: {\n name: \"abc\"\n }\n }\n);\n```\n\nI'm using the `!!` to cast the object to a boolean.\n\n========================================\n\nCode:\n```text\nmodel place {\n  id             Int              @id @default(dbgenerated(\"nextval('place_id_seq'::regclass)\"))\n  name           String\n  location       String @unique\n}\n```\n\n```text\nexport type Place = {\n  __typename?: 'Place';\n  name?: Maybe<Scalars['String']>;\n  location?: Maybe<Scalars['String']>;\n\n};\n```\n\n```text\nlet findPlace = await prisma.place.findUnique(\n        {\n          where: {\n            name: \"abc\"\n          }\n        }\n)\n```\n\n```text\nType '{ name: string; }' is not assignable to type 'placeWhereUniqueInput'.\n  Object literal may only specify known properties, and 'name' does not exist in type 'placeWhereUniqueInput'.ts(2322)\nindex.d.ts(1361, 5): The expected type comes from property 'where' which is declared here on type '{ select?: placeSelect | null | undefined; include?: placeInclude | null | undefined; rejectOnNotFound?: RejectOnNotFound | undefined; where: placeWhereUniqueInput; }'\n```\n\n```text\nname\n```\n\n```text\nlocation\n```\n\n```text\nschema.prisma\n```\n\n```js\nlet placeCount = await prisma.place.count(\n        {\n          where: {\n            name: \"abc\"\n          }\n        }\n)\n// placeCount == 0 implies does not exist\n```\n\n```text\nfindUnique\n```\n\n```text\ncount\n```\n\n```js\nconst exists = !!await prisma.place.findFirst(\n  {\n    where: {\n      name: \"abc\"\n    }\n  }\n);\n```\n\n```text\nfindUnique\n```\n\n```text\ncount\n```\n\n```text\nfindFirst\n```\n\n```text\nLIMIT 1\n```\n\n```text\n!!\n```\n\n========================================\n\nComments:\n- This is best because transmit less data.\n- I liked the `!!` cast","metadata":{"transformedAt":"2026-08-18T18:33:14.817Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":171,"estimatedTokens":825}}50{"id":"stack-67226972","source":"stackoverflow","questionId":67226972,"title":"Prisma - How to define compound unique constraint with fields in multiple models?","tags":["prisma","prisma-graphql","prisma2"],"text":"Title: Prisma - How to define compound unique constraint with fields in multiple models?\nTags: prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have this not so straightforward model relationship in Prisma. User ---- Course and I can't figure out how to ensure the Course title field is unique just among that user's created courses. In other words, I dont want one user to create multiple courses with the same name. But I want courses to exist with the same name with different Creators. (Only the creator has the TEACHER role in the Enrollment)\n\nThe problem I'm facing is, I don't know where to define a unique attribute and what fields to include. The fields I want to make a unique constraint on (Course name, Member who has TEACHER role) are across different models.\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n passwordHash String\n enrollments Enrollment[]\n}\n\nmodel Course {\n id Int @id @default(autoincrement())\n name String\n members Enrollment[]\n}\n\nmodel Enrollment {\n role UserRole @default(STUDENT)\n\n // Relation Fields\n userId Int\n courseId Int\n user User @relation(fields: [userId], references: [id])\n course Course @relation(fields: [courseId], references: [id])\n @@id([userId, courseId])\n @@index([userId, role])\n}\n```\n\n========================================\n\nCode:\n```text\nmodel User {\n  id                Int              @id @default(autoincrement())\n  email             String           @unique\n  passwordHash      String\n  enrollments       Enrollment[]\n}\n\nmodel Course {\n  id                Int              @id @default(autoincrement())\n  name              String\n  members           Enrollment[]\n}\n\nmodel Enrollment {\n  role              UserRole         @default(STUDENT)\n\n  // Relation Fields\n  userId            Int\n  courseId         Int\n  user              User             @relation(fields: [userId], references: [id])\n  course           Course          @relation(fields: [courseId], references: [id])\n  @@id([userId, courseId])\n  @@index([userId, role])\n}\n```\n\n```text\nmodel Course {\n  id                Int              @id @default(autoincrement())\n  name              String\n  members           Enrollment[]\n  creatorId         Int\n  creator           User             @relation(fields: [creatorId], references: [id])\n  @@unique([creatorId, name], name: \"courseIdentifier\")\n}\n```\n\n```text\nCourse\n```\n\n========================================\n\nComments:\n- Redundant insertions succeed. I guess applies the constraint on each individual field.\n- This is the solution to make a combination of fields unique: flaviocopes.com/prisma-multiple-fields-unique-key","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":86,"estimatedTokens":661}}51{"id":"stack-68922032","source":"stackoverflow","questionId":68922032,"title":"Prisma cannot authenticate database server","tags":["docker","docker-compose","prisma"],"text":"Title: Prisma cannot authenticate database server\nTags: docker, docker-compose, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using docker to initiate a postgres db:\n\n```\nversion: '3.8'\nservices:\n postgres:\n image: postgres:13\n restart: always\n environment:\n POSTGRES_USER: db_user\n POSTGRES_PASSWORD: db_password\n volumes:\n - postgres:/var/lib/postgresql/data\n ports:\n - '5432:5432'\nvolumes:\n postgres:\n```\n\nand in my `/.env` file I have:\n\n```\nDATABASE_URL=\"postgresql://db_user:db_password@localhost:5432/college_db?schema=public\"\n```\n\nI start docker:\n\n```\nPS C:\\Users\\alucardu\\Documents\\projects\\**-react> docker-compose up -d\nStarting **-react_postgres_1 ... done\n```\n\nCheck if the server is running:\n\n```\nPS C:\\Users\\alucardu\\Documents\\projects\\**-react> docker ps\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\ne0f9233ce34b postgres:13 \"docker-entrypoint.s…\" 2 minutes ago Up 33 seconds 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp **-react_postgres_1\n```\n\nBut when I run a Prisma migrate I get an authentication error:\n\n```\nPS C:\\Users\\alucardu\\Documents\\projects\\movieseat-react> npx prisma migrate dev --name \"init\"\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\": PostgreSQL database \"college_db\", schema \"public\" at \"localhost:5432\"\n\nError: P1000: Authentication failed against database server at `localhost`, the provided database credentials for `db_user` are not valid.\n\nPlease make sure to provide valid database credentials for the database server at `localhost`.\n```\n\nWhy is Prisma not matching the set `db_user` and `db_password` to the environment variables created in the docker yml?\n\n//edit.\n\nI've added a `college_db` database and a superuser called `db_user` and made it owner of the `college_db`:\n\nhttps://i.sstatic.net/2c0wf.png\n\nBut I'm still getting the same error.\n\n========================================\n\nTop Answer:\nIf you are still having this problem, check if you have postgres installed on the machine without docker and check if postgres is started on Windows and stop this process and try again\n\nenter image description here\n\n========================================\n\nCode:\n```text\nversion: '3.8'\nservices:\n  postgres:\n    image: postgres:13\n    restart: always\n    environment:\n      POSTGRES_USER: db_user\n      POSTGRES_PASSWORD: db_password\n    volumes:\n      - postgres:/var/lib/postgresql/data\n    ports:\n      - '5432:5432'\nvolumes:\n    postgres:\n```\n\n```text\nDATABASE_URL=\"postgresql://db_user:db_password@localhost:5432/college_db?schema=public\"\n```\n\n```text\nPS C:\\Users\\alucardu\\Documents\\projects\\**-react> docker-compose up -d\nStarting **-react_postgres_1 ... done\n```\n\n```text\nPS C:\\Users\\alucardu\\Documents\\projects\\**-react> docker ps\nCONTAINER ID   IMAGE         COMMAND                  CREATED         STATUS          PORTS                                       NAMES\ne0f9233ce34b   postgres:13   \"docker-entrypoint.s…\"   2 minutes ago   Up 33 seconds   0.0.0.0:5432->5432/tcp, :::5432->5432/tcp   **-react_postgres_1\n```\n\n```text\nPS C:\\Users\\alucardu\\Documents\\projects\\movieseat-react> npx prisma migrate dev --name \"init\"\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\": PostgreSQL database \"college_db\", schema \"public\" at \"localhost:5432\"\n\nError: P1000: Authentication failed against database server at `localhost`, the provided database credentials for `db_user` are not valid.\n\nPlease make sure to provide valid database credentials for the database server at `localhost`.\n```\n\n```text\n/.env\n```\n\n```text\ndb_user\n```\n\n```text\ndb_password\n```\n\n```text\ncollege_db\n```\n\n```text\ndb_user\n```\n\n```text\ncollege_db\n```\n\n```text\nPOSTGRES_DB: college_db\n```\n\n```yaml\nversion: '3.8'\nservices:\n  postgres:\n    image: postgres:13\n    restart: always\n    environment:\n      POSTGRES_USER: db_user\n      POSTGRES_PASSWORD: db_password\n    volumes:\n      - postgres:/var/lib/postgresql/data\n    ports:\n      - 5432:5432\nvolumes:\n    postgres:\n```\n\n```yaml\nersion: '3.8'\nservices:\n  postgres:\n    image: postgres:13\n    restart: always\n    environment:\n      POSTGRES_USER: db_user\n      POSTGRES_PASSWORD: db_password\n    volumes:\n      - postgres:/var/lib/postgresql/data\n    expose:\n      - 5432\n    ports:\n      - 5432\nvolumes:\n    postgres:\n```\n\n```text\ndocker stop $(docker ps -aq)\ndocker rm $(docker ps -aq)\ndocker rmi $(docker images -q)\ndocker volume rm $(docker volume ls -q)\ndocker builder prune\n```\n\n```text\ndocker stop <container-id>\ndocker rm <container-id>\ndocker volume rm <volume-id>\ndocker builder prune\n```\n\n========================================\n\nComments:\n- Issue is probably because of host resolving. Have you tried `127.0.0.1` instead of localhost ?\n- `P1000: Authentication failed against database server at`127.0.0.1`, the provided database credentials for`db_user` are not valid.`, too bad no effect.\n- Makes sense, but it's not the issue. I've added the `POSTGRES_DB` to the variables, but still the same error.\n- Have you deleted also the volume when you tried?\n- Yes, I've removed everything that was currently running in docker and rerun docker compose.\n- Had the same issue and was pulling my hair cus I could connect fine from my WSL xD thank you!","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":209,"estimatedTokens":1310}}52{"id":"stack-68670004","source":"stackoverflow","questionId":68670004,"title":"Prisma delete many to many relationship with Composite Key","tags":["mysql","prisma","prisma2"],"text":"Title: Prisma delete many to many relationship with Composite Key\nTags: mysql, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have this schema here:\n\n```\nmodel label {\n title String @id @db.VarChar(16)\n color String @db.VarChar(16)\n labelplaylist labelplaylist[]\n}\n\nmodel labelplaylist {\n playlistId Int\n labelId String @db.VarChar(16)\n label label @relation(fields: [labelId], references: [title])\n playlist playlist @relation(fields: [playlistId], references: [id])\n\n @@id([playlistId, labelId])\n @@index([labelId], name: \"labelId\")\n}\n\nmodel playlist {\n id Int @id @default(autoincrement())\n createdAt DateTime? @default(now()) @db.DateTime(0)\n title String @db.VarChar(100)\n labelplaylist labelplaylist[]\n\n @@index([userId], name: \"userId\")\n}\n```\n\nAnd I would like to delete only the relation between the label and the playlist table. I tried it to do like this:\n\n```\nconst deleteRelation = await prisma.labelplaylist.delete({\n where: {\n playlistId_labelId: \n },\n})\n```\n\nI have the primary key of the label and playlist table, but I don't know how I get the primary key => playlistId_labelId.\n\nThank's for helping out.\n\n========================================\n\nTop Answer:\nSince it's an **explicit** many-to-many relationship, nested `deleteMany` only deletes relation table records, acting like a `disconnect`. You can then write your query like that:\n\n```\nawait req.db.playlist.update({\n data: {\n labels: {\n deleteMany: {},\n },\n },\n where: {\n id: labelId,\n },\n})\n```\n\nor the other way around.\n\nIt won't delete your related table records but only the links between them.\n\n========================================\n\nCode:\n```text\nmodel label {\n  title         String          @id @db.VarChar(16)\n  color         String          @db.VarChar(16)\n  labelplaylist labelplaylist[]\n}\n\nmodel labelplaylist {\n  playlistId Int\n  labelId    String   @db.VarChar(16)\n  label      label    @relation(fields: [labelId], references: [title])\n  playlist   playlist @relation(fields: [playlistId], references: [id])\n\n  @@id([playlistId, labelId])\n  @@index([labelId], name: \"labelId\")\n}\n\nmodel playlist {\n  id              Int             @id @default(autoincrement())\n  createdAt       DateTime?       @default(now()) @db.DateTime(0)\n  title           String          @db.VarChar(100)\n  labelplaylist   labelplaylist[]\n\n  @@index([userId], name: \"userId\")\n}\n```\n\n```text\nconst deleteRelation = await prisma.labelplaylist.delete({\n    where: {\n        playlistId_labelId: \n    },\n})\n```\n\n```js\nconst deleteRelation = await prisma.labelplaylist.delete({\n        where: {\n            playlistId_labelId: {\n                playlistId: playListIdVariable, //replace with appropriate variable\n                labelId: labelIdVariable, //replace with appropriate variable\n            },\n        },\n    });\n```\n\n```text\nwhere\n```\n\n```js\nawait req.db.playlist.update({\n  data: {\n    labels: {\n      deleteMany: {},\n    },\n  },\n  where: {\n    id: labelId,\n  },\n})\n```\n\n```text\ndeleteMany\n```\n\n```text\ndisconnect\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":143,"estimatedTokens":750}}53{"id":"stack-73603874","source":"stackoverflow","questionId":73603874,"title":"How to add multiple ids to a connect on Prisma","tags":["node.js","typescript","prisma"],"text":"Title: How to add multiple ids to a connect on Prisma\nTags: node.js, typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nReading the prisma docs i find that is possible to create a connection where i make the plan have one item connected (as i did below). but i want to dinamic pass an array of strings (that items prop) that have ids of items to connect when creating my plan.\n\nThe code below works well, but i dont know how to pass that array n connect every item that match one of the ids on the array\n\n```\nconst plan = await this.connection.create({\n data: {\n name,\n description,\n type,\n picture,\n productionPrice,\n price,\n items: {\n connect: [\n {\n id: items,\n },\n ],\n },\n },\n include: {\n items: true,\n },\n });\n\n return plan;\n```\n\n========================================\n\nCode:\n```text\nconst plan = await this.connection.create({\n      data: {\n        name,\n        description,\n        type,\n        picture,\n        productionPrice,\n        price,\n        items: {\n          connect: [\n            {\n              id: items,\n            },\n          ],\n        },\n      },\n      include: {\n        items: true,\n      },\n    });\n\n    return plan;\n```\n\n```js\nconst plan = await this.connection.create({\n      data: {\n        name,\n        description,\n        type,\n        picture,\n        productionPrice,\n        price,\n        items: {\n          connect: [\n            {\n              id: 1,\n            },\n            {\n              id: 2,\n            },\n            {\n              id: 3,\n            },\n          ],\n        },\n      },\n      include: {\n        items: true,\n      },\n    });\n```\n\n```js\n...\n        items: {\n          connect: items.map(id => ({ id }),\n        },\n...\n```\n\n```text\nitems\n```\n\n========================================\n\nComments:\n- I knew what i need to use (map) but i wasnt sure about how do this apsdoksapda i think is because was very late n i was coding since i dkn when. thnks buddy","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":483}}54{"id":"stack-67625517","source":"stackoverflow","questionId":67625517,"title":"Prisma @db.Time(x) - what is x?","tags":["prisma"],"text":"Title: Prisma @db.Time(x) - what is x?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nAfter running the `npx prisma introspect` in the console, the `startTime` attribute was set to `@db.Time(6)` in my `schema.prisma` file.\n\n```\nmodel Table {\n id String @id @default(uuid())\n startTime DateTime @map(\"start_time\") @db.Time(6)\n}\n```\n\nWhat does `x` mean in `@db.Time(x)` in Prisma schema? Documentation link\n\nP.S. I use `PosgreSQL` as database\n\n========================================\n\nCode:\n```text\nmodel Table {\n  id           String     @id @default(uuid())\n  startTime    DateTime   @map(\"start_time\") @db.Time(6)\n}\n```\n\n```text\nnpx prisma introspect\n```\n\n```text\nstartTime\n```\n\n```text\n@db.Time(6)\n```\n\n```text\nschema.prisma\n```\n\n```text\nx\n```\n\n```text\n@db.Time(x)\n```\n\n```text\nPosgreSQL\n```\n\n```text\nx\n```\n\n```text\ntime\n```\n\n========================================\n\nComments:\n- how are you sending that time value eg startTime: \"12:00:00\" like this?\n- Thank you! It's shocking how difficult this information was to find.","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":69,"estimatedTokens":257}}55{"id":"stack-66738563","source":"stackoverflow","questionId":66738563,"title":"Error importing PrismaClient in code compiled from typescript [SyntaxError: Named export 'PrismaClient' not found]","tags":["node.js","typescript","express","prisma","ts-node-dev"],"text":"Title: Error importing PrismaClient in code compiled from typescript [SyntaxError: Named export 'PrismaClient' not found]\nTags: node.js, typescript, express, prisma, ts-node-dev\nSource: Stack Overflow\n\nQuestion:\nIn server.ts, importing PrismaClient like this:\n\n```\nimport { PrismaClient } from '@prisma/client';\n\nexport const prisma = new PrismaClient();\n```\n\nthrows an Error when building with tsc and running the compiled code:\n\n```\nyarn run build && yarn run start\n\nimport { PrismaClient } from '@prisma/client';\n ^^^^^^^^^^^^\nSyntaxError: Named export 'PrismaClient' not found. The requested module '@prisma/client' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\n import pkg from '@prisma/client';\n const { PrismaClient } = pkg;\n \n at ModuleJob._instantiate (internal/modules/esm/module_job.js:104:21)\n at async ModuleJob.run (internal/modules/esm/module_job.js:149:5)\n at async Loader.import (internal/modules/esm/loader.js:166:24)\n at async Object.loadESM (internal/process/esm_loader.js:68:5)\n error Command failed with exit code 1.\n```\n\nSo I did what was recommended and changed the code to:\n\n```\nimport Prisma from '@prisma/client';\n\nconst { PrismaClient } = Prisma;\nexport const prisma = new PrismaClient();\n```\n\nAnd this code works after building with tsc and running the resulting code. But now running the typescript files with ts-node-dev throws this Error:\n\n```\nyarn run dev\n\nTypeError: Cannot destructure property 'PrismaClient' of 'client_1.default' as it is undefined.\n at Object. (C:\\Users\\gfs10\\Projetos\\rest-api\\src\\server.ts:11:9)\n at Module._compile (internal/modules/cjs/loader.js:1063:30)\n at Module._compile (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\source-map-support\\source-map-support.js:547:25)\n at Module.m._compile (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-9753341767331849.js:69:33)\n at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n at require.extensions. (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-9753341767331849.js:71:20)\n at Object.nodeDevHook [as .ts] (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\ts-node-dev\\lib\\hook.js:63:13)\n at Module.load (internal/modules/cjs/loader.js:928:32)\n at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n at Module.require (internal/modules/cjs/loader.js:952:19)\n[ERROR] 19:03:38 TypeError: Cannot destructure property 'PrismaClient' of 'client_1.default' as it is undefined.\n```\n\nAnd changing the code to:\n\n```\nimport Prisma from '@prisma/client';\n\nexport const prisma = new Prisma.PrismaClient();\n```\n\nthrows this error:\n\n```\nyarn run dev\n\nTypeError: Cannot read property 'PrismaClient' of undefined\n at Object. (C:\\Users\\gfs10\\Projetos\\rest-api\\src\\server.ts:11:34)\n at Module._compile (internal/modules/cjs/loader.js:1063:30)\n at Module._compile (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\source-map-support\\source-map-support.js:547:25)\n at Module.m._compile (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-7015369495927739.js:69:33)\n at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n at require.extensions. (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-7015369495927739.js:71:20)\n at Object.nodeDevHook [as .ts] (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\ts-node-dev\\lib\\hook.js:63:13)\n at Module.load (internal/modules/cjs/loader.js:928:32)\n at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n at Module.require (internal/modules/cjs/loader.js:952:19)\n[ERROR] 19:09:01 TypeError: Cannot read property 'PrismaClient' of undefined\n```\n\nHow come? How can I make both work at the same time?\n\nMy tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./build/\",\n \"rootDir\": \"./src/\",\n \"strict\": true,\n \"alwaysStrict\": true,\n \"noImplicitAny\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noImplicitReturns\": true,\n \"strictNullChecks\": true,\n \"strictPropertyInitialization\": true,\n \"strictBindCallApply\": true,\n \"noImplicitThis\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"esModuleInterop\": true,\n \"declaration\": true\n }\n}\n```\n\nMy package.json:\n\n```\n{\n \"name\": \"rest-api\",\n \"version\": \"1.0.0\",\n \"description\": \"A REST API boilerplate.\",\n \"main\": \"server.ts\",\n \"author\": \"Gledyson Ferreira\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"node --experimental-specifier-resolution=node build/server.js\",\n \"dev\": \"SET NODE_ENV=development&& ts-node-dev --clear src/server.ts\",\n \"build\": \"tsc\",\n \"lint\": \"eslint --ext .ts .\"\n },\n \"devDependencies\": {\n \"@typescript-eslint/eslint-plugin\": \"^4.18.0\",\n \"@typescript-eslint/parser\": \"^4.18.0\",\n \"eslint\": \"^7.22.0\",\n \"prisma\": \"^2.19.0\",\n \"ts-node-dev\": \"^1.1.6\",\n \"typescript\": \"^4.2.3\"\n },\n \"dependencies\": {\n \"@prisma/client\": \"^2.19.0\",\n \"@types/bcrypt\": \"^3.0.0\",\n \"@types/cors\": \"^2.8.10\",\n \"@types/express\": \"^4.17.11\",\n \"@types/jsonwebtoken\": \"^8.5.1\",\n \"@types/morgan\": \"^1.9.2\",\n \"@types/node\": \"^14.14.35\",\n \"@types/passport\": \"^1.0.6\",\n \"@types/passport-jwt\": \"^3.0.5\",\n \"bcrypt\": \"^5.0.1\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^4.17.1\",\n \"jsonwebtoken\": \"^8.5.1\",\n \"morgan\": \"^1.10.0\",\n \"passport\": \"^0.4.1\",\n \"passport-jwt\": \"^4.0.0\"\n }\n}\n```\n\nMy server.ts\n\n```\nimport express from 'express';\nimport Prisma from '@prisma/client';\nimport config from './config';\nimport api from './api';\nimport middleware from './middlewares';\nimport morgan from 'morgan';\nimport cors from 'cors';\nimport passport from 'passport';\nimport setReqUser from './services/passport';\n\nexport const prisma = new Prisma.PrismaClient();\nconst app = express();\n\napp.disable('x-powered-by');\napp.use(express.json());\napp.use(morgan('tiny'));\napp.use(cors());\napp.use(passport.initialize());\nsetReqUser(passport);\n\napp.use('/api/v1', api.authRoute);\napp.use('/api/v1/users', api.userRoute);\n\napp.use(middleware.unknownEndpoint);\napp.use(middleware.errorHandler);\n\napp.listen(config.port, () => {\n console.log(`\n ################################################\n \n Server running on port ${config.port} in ${config.env} mode.\n\n ################################################\n `);\n});\n```\n\n========================================\n\nTop Answer:\nIf you just cloned this project then it's likely that you didn't generate the prisma client yet. I've ran `npx prisma generate` and it seemed to fix it.\n\n========================================\n\nCode:\n```text\nimport { PrismaClient } from '@prisma/client';\n\nexport const prisma = new PrismaClient();\n```\n\n```text\nyarn run build && yarn run start\n\nimport { PrismaClient } from '@prisma/client';\n         ^^^^^^^^^^^^\nSyntaxError: Named export 'PrismaClient' not found. The requested module '@prisma/client' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\n    import pkg from '@prisma/client';\n    const { PrismaClient } = pkg;\n    \n        at ModuleJob._instantiate (internal/modules/esm/module_job.js:104:21)\n        at async ModuleJob.run (internal/modules/esm/module_job.js:149:5)\n        at async Loader.import (internal/modules/esm/loader.js:166:24)\n        at async Object.loadESM (internal/process/esm_loader.js:68:5)\n    error Command failed with exit code 1.\n```\n\n```text\nimport Prisma from '@prisma/client';\n\nconst { PrismaClient } = Prisma;\nexport const prisma = new PrismaClient();\n```\n\n```text\nyarn run dev\n\nTypeError: Cannot destructure property 'PrismaClient' of 'client_1.default' as it is undefined.\n    at Object.<anonymous> (C:\\Users\\gfs10\\Projetos\\rest-api\\src\\server.ts:11:9)\n    at Module._compile (internal/modules/cjs/loader.js:1063:30)\n    at Module._compile (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\source-map-support\\source-map-support.js:547:25)\n    at Module.m._compile (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-9753341767331849.js:69:33)\n    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n    at require.extensions.<computed> (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-9753341767331849.js:71:20)\n    at Object.nodeDevHook [as .ts] (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\ts-node-dev\\lib\\hook.js:63:13)\n    at Module.load (internal/modules/cjs/loader.js:928:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n    at Module.require (internal/modules/cjs/loader.js:952:19)\n[ERROR] 19:03:38 TypeError: Cannot destructure property 'PrismaClient' of 'client_1.default' as it is undefined.\n```\n\n```text\nimport Prisma from '@prisma/client';\n\nexport const prisma = new Prisma.PrismaClient();\n```\n\n```text\nyarn run dev\n\nTypeError: Cannot read property 'PrismaClient' of undefined\n    at Object.<anonymous> (C:\\Users\\gfs10\\Projetos\\rest-api\\src\\server.ts:11:34)\n    at Module._compile (internal/modules/cjs/loader.js:1063:30)\n    at Module._compile (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\source-map-support\\source-map-support.js:547:25)\n    at Module.m._compile (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-7015369495927739.js:69:33)\n    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)\n    at require.extensions.<computed> (C:\\Users\\gfs10\\AppData\\Local\\Temp\\ts-node-dev-hook-7015369495927739.js:71:20)\n    at Object.nodeDevHook [as .ts] (C:\\Users\\gfs10\\Projetos\\rest-api\\node_modules\\ts-node-dev\\lib\\hook.js:63:13)\n    at Module.load (internal/modules/cjs/loader.js:928:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:769:14)\n    at Module.require (internal/modules/cjs/loader.js:952:19)\n[ERROR] 19:09:01 TypeError: Cannot read property 'PrismaClient' of undefined\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"moduleResolution\": \"node\",\n    \"outDir\": \"./build/\",\n    \"rootDir\": \"./src/\",\n    \"strict\": true,\n    \"alwaysStrict\": true,\n    \"noImplicitAny\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noImplicitReturns\": true,\n    \"strictNullChecks\": true,\n    \"strictPropertyInitialization\": true,\n    \"strictBindCallApply\": true,\n    \"noImplicitThis\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"esModuleInterop\": true,\n    \"declaration\": true\n  }\n}\n```\n\n```text\n{\n  \"name\": \"rest-api\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A REST API boilerplate.\",\n  \"main\": \"server.ts\",\n  \"author\": \"Gledyson Ferreira\",\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"start\": \"node --experimental-specifier-resolution=node build/server.js\",\n    \"dev\": \"SET NODE_ENV=development&& ts-node-dev --clear src/server.ts\",\n    \"build\": \"tsc\",\n    \"lint\": \"eslint --ext .ts .\"\n  },\n  \"devDependencies\": {\n    \"@typescript-eslint/eslint-plugin\": \"^4.18.0\",\n    \"@typescript-eslint/parser\": \"^4.18.0\",\n    \"eslint\": \"^7.22.0\",\n    \"prisma\": \"^2.19.0\",\n    \"ts-node-dev\": \"^1.1.6\",\n    \"typescript\": \"^4.2.3\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"^2.19.0\",\n    \"@types/bcrypt\": \"^3.0.0\",\n    \"@types/cors\": \"^2.8.10\",\n    \"@types/express\": \"^4.17.11\",\n    \"@types/jsonwebtoken\": \"^8.5.1\",\n    \"@types/morgan\": \"^1.9.2\",\n    \"@types/node\": \"^14.14.35\",\n    \"@types/passport\": \"^1.0.6\",\n    \"@types/passport-jwt\": \"^3.0.5\",\n    \"bcrypt\": \"^5.0.1\",\n    \"cors\": \"^2.8.5\",\n    \"express\": \"^4.17.1\",\n    \"jsonwebtoken\": \"^8.5.1\",\n    \"morgan\": \"^1.10.0\",\n    \"passport\": \"^0.4.1\",\n    \"passport-jwt\": \"^4.0.0\"\n  }\n}\n```\n\n```text\nimport express from 'express';\nimport Prisma from '@prisma/client';\nimport config from './config';\nimport api from './api';\nimport middleware from './middlewares';\nimport morgan from 'morgan';\nimport cors from 'cors';\nimport passport from 'passport';\nimport setReqUser from './services/passport';\n\nexport const prisma = new Prisma.PrismaClient();\nconst app = express();\n\napp.disable('x-powered-by');\napp.use(express.json());\napp.use(morgan('tiny'));\napp.use(cors());\napp.use(passport.initialize());\nsetReqUser(passport);\n\napp.use('/api/v1', api.authRoute);\napp.use('/api/v1/users', api.userRoute);\n\napp.use(middleware.unknownEndpoint);\napp.use(middleware.errorHandler);\n\napp.listen(config.port, () => {\n  console.log(`\n    ################################################\n    \n    Server running on port ${config.port} in ${config.env} mode.\n\n    ################################################\n  `);\n});\n```\n\n```text\nconst { PrismaClient } = pkg;\n```\n\n```text\nclass MyClass {\n  prisma: Prisma.PrismaClient\n\n  def constructor(props) {\n    if (!props?.prisma) {\n      const { PrismaClient } = Prisma\n      this.prisma = new PrismaClient({\n        log: ['error']\n      })\n    } else {\n      this.prisma = props.prisma\n    }\n  }\n}\n```\n\n```text\nconst mockPrisma = mockDeep<OriginalPrismaClient>();\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\ntarget\n```\n\n```text\ntsconfig.json\n```\n\n```text\nES2018\n```\n\n```text\nnpx prisma generate\n```\n\n```bash\nnpm i  prisma  @prisma/client\n\nnpx  npx prisma generate\n```\n\n```text\ntsconfig.ts\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  // output   = \"../generated/prisma\"  ---Comment out this line\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n```text\nnpx prisma generate\n```\n\n========================================\n\nComments:\n- I used `import { PrismaClient } from \"@prisma&#47;client\"` for a while and it was working on production. For some unknown reason it does not work anymore. The deconstruction trick worked!\n- this solves it. restart code editor to reset cache if this isn't working for you upon initial try\n- This does not solve it for me.\n- It solved the issue for me as well after running `npx prisma generate`. If you use `pnpm`, do not forget to add: `hoist-pattern[]=*prisma*`.\n- Please use proper code formatting, and include the relevant code as code block (not as image).","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":470,"estimatedTokens":3448}}56{"id":"stack-73437060","source":"stackoverflow","questionId":73437060,"title":"TypeError when using cursor in Prisma","tags":["typescript","next.js","backend","api-design","prisma"],"text":"Title: TypeError when using cursor in Prisma\nTags: typescript, next.js, backend, api-design, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using Prisma (4.2.1) in a Next.js API Route for cursor-based pagination of posts.\n\nWhen I pass the cursor to the API endpoint, I get the following error message (500) in the console:\n\n```\nTypeError: Cannot read properties of undefined (reading 'createdAt')\n at getPost (webpack-internal:///(api)/./lib/api/post.ts:67:46)\nerror - TypeError [ERR_INVALID_ARG_TYPE]: The \"string\" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of TypeError\n```\n\nI'm using Postman to access the API endpoint.\n\nWhen I remove the cursor from the API Route, there are no errors and the posts are returned as expected.\n\nI've tried upgrading to the latest Prisma version (4.2.1), using .toString() on the cursor, and changing the AllPosts interface to 'any' but I've been unable to solve the TypeError.\n\nHow can I fix this error and get Prisma to accept the cursor as valid?\n\n### API Route\n\n```\nimport prisma from \"@/lib/prisma\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\nimport type { Post, Site } from \".prisma/client\";\nimport type { Session } from \"next-auth\";\nimport { revalidate } from \"@/lib/revalidate\";\nimport type { WithSitePost } from \"@/types\";\n\ninterface AllPosts {\n posts: Array;\n site: Site | null;\n}\n\nexport async function getPost(\n req: NextApiRequest,\n res: NextApiResponse,\n session: Session\n): Promise> {\n const { postId, siteId, published, cursor } = req.query;\n\n if (\n Array.isArray(postId) ||\n Array.isArray(siteId) ||\n Array.isArray(published) ||\n Array.isArray(cursor)\n )\n return res.status(400).end(\"Bad request. Query parameters are not valid.\");\n\n if (!session.user.id)\n return res.status(500).end(\"Server failed to get session user ID\");\n\n try {\n if (postId) {\n const post = await prisma.post.findFirst({\n where: {\n id: postId,\n site: {\n user: {\n id: session.user.id,\n },\n },\n },\n include: {\n site: true,\n },\n });\n\n return res.status(200).json(post);\n }\n\n const site = await prisma.site.findFirst({\n where: {\n id: siteId,\n user: {\n id: session.user.id,\n },\n },\n });\n\n const posts = !site\n ? []\n : await prisma.post.findMany({\n take: 10,\n skip: cursor === undefined ? 0 : 1,\n cursor: {\n id: cursor,\n },\n where: {\n site: {\n id: siteId,\n },\n published: JSON.parse(published || \"true\"),\n },\n orderBy: {\n createdAt: \"desc\",\n },\n });\n\n const lastPostInResults = posts[9];\n const nextCursor = lastPostInResults.createdAt;\n\n return res.status(200).json({\n posts,\n site,\n nextCursor,\n });\n } catch (error) {\n console.error(error);\n return res.status(500).end(error);\n }\n}\n```\n\n### Prisma Schema\n\n```\nmodel Post {\n id String @id @default(cuid())\n title String? @db.Text\n content String? @db.LongText\n slug String @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n published Boolean @default(false)\n site Site? @relation(fields: [siteId], references: [id], onDelete: Cascade)\n siteId String?\n\n @@unique([id, siteId], name: \"post_site_constraint\")\n}\n\nmodel Site {\n id String @id @default(cuid())\n name String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User? @relation(fields: [userId], references: [id])\n userId String?\n posts Post[]\n}\n```\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read properties of undefined (reading 'createdAt')\n    at getPost (webpack-internal:///(api)/./lib/api/post.ts:67:46)\nerror - TypeError [ERR_INVALID_ARG_TYPE]: The \"string\" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of TypeError\n```\n\n```js\nimport prisma from \"@/lib/prisma\";\nimport type { NextApiRequest, NextApiResponse } from \"next\";\nimport type { Post, Site } from \".prisma/client\";\nimport type { Session } from \"next-auth\";\nimport { revalidate } from \"@/lib/revalidate\";\nimport type { WithSitePost } from \"@/types\";\n\ninterface AllPosts {\n  posts: Array<Post>;\n  site: Site | null;\n}\n\nexport async function getPost(\n  req: NextApiRequest,\n  res: NextApiResponse,\n  session: Session\n): Promise<void | NextApiResponse<AllPosts | (WithSitePost | null)>> {\n  const { postId, siteId, published, cursor } = req.query;\n\n  if (\n    Array.isArray(postId) ||\n    Array.isArray(siteId) ||\n    Array.isArray(published) ||\n    Array.isArray(cursor)\n  )\n    return res.status(400).end(\"Bad request. Query parameters are not valid.\");\n\n  if (!session.user.id)\n    return res.status(500).end(\"Server failed to get session user ID\");\n\n  try {\n    if (postId) {\n      const post = await prisma.post.findFirst({\n        where: {\n          id: postId,\n          site: {\n            user: {\n              id: session.user.id,\n            },\n          },\n        },\n        include: {\n          site: true,\n        },\n      });\n\n      return res.status(200).json(post);\n    }\n\n    const site = await prisma.site.findFirst({\n      where: {\n        id: siteId,\n        user: {\n          id: session.user.id,\n        },\n      },\n    });\n\n    const posts = !site\n      ? []\n      : await prisma.post.findMany({\n          take: 10,\n          skip: cursor === undefined ? 0 : 1,\n          cursor: {\n            id: cursor,\n          },\n          where: {\n            site: {\n              id: siteId,\n            },\n            published: JSON.parse(published || \"true\"),\n          },\n          orderBy: {\n            createdAt: \"desc\",\n          },\n        });\n\n    const lastPostInResults = posts[9];\n    const nextCursor = lastPostInResults.createdAt;\n\n    return res.status(200).json({\n      posts,\n      site,\n      nextCursor,\n    });\n  } catch (error) {\n    console.error(error);\n    return res.status(500).end(error);\n  }\n}\n```\n\n```js\nmodel Post {\n  id            String   @id @default(cuid())\n  title         String?  @db.Text\n  content       String?  @db.LongText\n  slug          String   @default(cuid())\n  createdAt     DateTime @default(now())\n  updatedAt     DateTime @updatedAt\n  published     Boolean  @default(false)\n  site          Site?    @relation(fields: [siteId], references: [id], onDelete: Cascade)\n  siteId        String?\n\n  @@unique([id, siteId], name: \"post_site_constraint\")\n}\n\nmodel Site {\n  id            String        @id @default(cuid())\n  name          String?\n  createdAt     DateTime      @default(now())\n  updatedAt     DateTime      @updatedAt\n  user          User?         @relation(fields: [userId], references: [id])\n  userId        String?\n  posts         Post[]\n}\n```\n\n```text\nmodel Post {\n  createdAt     DateTime @default(now())\n  ...\n}\n```\n\n```text\n@unique\n```\n\n```text\nprisma generate\n```\n\n========================================\n\nComments:\n- How are you making the request to your API endpoint?\n- @AustinCrim I made the request to my API endpoint using Postman.","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":294,"estimatedTokens":1703}}57{"id":"stack-57577464","source":"stackoverflow","questionId":57577464,"title":"Subscriptions not working with Prisma 2 and Nexus?","tags":["javascript","graphql","prisma","prisma-graphql","nexus-prisma"],"text":"Title: Subscriptions not working with Prisma 2 and Nexus?\nTags: javascript, graphql, prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nSubscriptions with Nexus are undocumented but I searched Github and tried every example in the book. It's just not working for me.\n\nI have cloned Prisma2 GraphQL boilerplate project & my files are as follows:\n\n### prisma/schema.prisma\n\n```\ndatasource db {\n provider = \"sqlite\"\n url = \"file:dev.db\"\n default = true\n}\n\ngenerator photon {\n provider = \"photonjs\"\n}\n\ngenerator nexus_prisma {\n provider = \"nexus-prisma\"\n}\n\nmodel Pokemon {\n id String @default(cuid()) @id @unique\n number Int @unique\n name String\n attacks PokemonAttack?\n}\n\nmodel PokemonAttack {\n id Int @id\n special Attack[]\n}\n\nmodel Attack {\n id Int @id\n name String\n damage String\n}\n```\n\n### src/index.js\n\n```\nconst { GraphQLServer } = require('graphql-yoga')\nconst { join } = require('path')\nconst { makeSchema, objectType, idArg, stringArg, subscriptionField } = require('@prisma/nexus')\nconst Photon = require('@generated/photon')\nconst { nexusPrismaPlugin } = require('@generated/nexus-prisma')\n\nconst photon = new Photon()\n\nconst nexusPrisma = nexusPrismaPlugin({\n photon: ctx => ctx.photon,\n})\n\nconst Attack = objectType({\n name: \"Attack\",\n definition(t) {\n t.model.id()\n t.model.name()\n t.model.damage()\n }\n})\n\nconst PokemonAttack = objectType({\n name: \"PokemonAttack\",\n definition(t) {\n t.model.id()\n t.model.special()\n }\n})\n\nconst Pokemon = objectType({\n name: \"Pokemon\",\n definition(t) {\n t.model.id()\n t.model.number()\n t.model.name()\n t.model.attacks()\n }\n})\n\nconst Query = objectType({\n name: 'Query',\n definition(t) {\n t.crud.findManyPokemon({\n alias: 'pokemons'\n })\n t.list.field('pokemon', {\n type: 'Pokemon',\n args: {\n name: stringArg(),\n },\n resolve: (parent, { name }, ctx) => {\n return ctx.photon.pokemon.findMany({\n where: {\n name\n }\n })\n },\n })\n },\n})\n\nconst Mutation = objectType({\n name: 'Mutation',\n definition(t) {\n t.crud.createOnePokemon({ alias: 'addPokemon' })\n },\n})\n\nconst Subscription = subscriptionField('newPokemon', {\n type: 'Pokemon',\n subscribe: (parent, args, ctx) => {\n return ctx.photon.$subscribe.pokemon()\n },\n resolve: payload => payload\n})\n\nconst schema = makeSchema({\n types: [Query, Mutation, Subscription, Pokemon, Attack, PokemonAttack, nexusPrisma],\n outputs: {\n schema: join(__dirname, '/schema.graphql')\n },\n typegenAutoConfig: {\n sources: [\n {\n source: '@generated/photon',\n alias: 'photon',\n },\n ],\n },\n})\n\nconst server = new GraphQLServer({\n schema,\n context: request => {\n return {\n ...request,\n photon,\n }\n },\n})\n\nserver.start(() => console.log(`🚀 Server ready at http://localhost:4000`))\n```\n\nThe related part is the `Subscription` which I don't know why it's not working or how it's supposed to work.\n\nI searched Github for this query which results in all projects using `Subscriptions`.\n\nI also found out this commit in this project to be relevant to my answer. Posting the related code here for brevity:\n\n```\nimport { subscriptionField } from 'nexus';\nimport { idArg } from 'nexus/dist/core';\nimport { Context } from './types';\n\n export const PollResultSubscription = subscriptionField('pollResult', {\n type: 'AnswerSubscriptionPayload',\n args: {\n pollId: idArg(),\n },\n subscribe(_: any, { pollId }: { pollId: string }, context: Context) {\n // Subscribe to changes on answers in the given poll\n return context.prisma.$subscribe.answer({\n node: { poll: { id: pollId } },\n });\n },\n resolve(payload: any) {\n return payload;\n },\n});\n```\n\nWhich is similar to what I do. But they do have `AnswerSubscriptionPayload` & I don't get any generated type that contains `Subscription` in it.\n\nHow do I solve this? I think I am doing everything right but it's still not working. Every example on GitHub is similar to above & even I am doing the same thing.\n\nAny suggestions?\n\nEdit: Subscriptions aren't implemented yet :(\n\n========================================\n\nTop Answer:\nI seem to have got this working despite subscriptions not being implemented. I have a working pubsub proof of concept based off the prisma2 boilerplate and Ben Awad's video tutorial https://youtu.be/146AypcFvAU . Should be able to get this up and running with redis and websockets to handle subscriptions until the prisma2 version is ready.\n\nhttps://github.com/ryanking1809/prisma2_subscriptions\n\n========================================\n\nCode:\n```text\ndatasource db {\n  provider = \"sqlite\"\n  url      = \"file:dev.db\"\n  default  = true\n}\n\ngenerator photon {\n  provider = \"photonjs\"\n}\n\ngenerator nexus_prisma {\n  provider = \"nexus-prisma\"\n}\n\nmodel Pokemon {\n  id      String         @default(cuid()) @id @unique\n  number  Int            @unique\n  name    String\n  attacks PokemonAttack?\n}\n\nmodel PokemonAttack {\n  id      Int      @id\n  special Attack[]\n}\n\nmodel Attack {\n  id     Int    @id\n  name   String\n  damage String\n}\n```\n\n```text\nconst { GraphQLServer } = require('graphql-yoga')\nconst { join } = require('path')\nconst { makeSchema, objectType, idArg, stringArg, subscriptionField } = require('@prisma/nexus')\nconst Photon = require('@generated/photon')\nconst { nexusPrismaPlugin } = require('@generated/nexus-prisma')\n\nconst photon = new Photon()\n\nconst nexusPrisma = nexusPrismaPlugin({\n  photon: ctx => ctx.photon,\n})\n\nconst Attack = objectType({\n  name: \"Attack\",\n  definition(t) {\n    t.model.id()\n    t.model.name()\n    t.model.damage()\n  }\n})\n\nconst PokemonAttack = objectType({\n  name: \"PokemonAttack\",\n  definition(t) {\n    t.model.id()\n    t.model.special()\n  }\n})\n\nconst Pokemon = objectType({\n  name: \"Pokemon\",\n  definition(t) {\n    t.model.id()\n    t.model.number()\n    t.model.name()\n    t.model.attacks()\n  }\n})\n\nconst Query = objectType({\n  name: 'Query',\n  definition(t) {\n    t.crud.findManyPokemon({\n      alias: 'pokemons'\n    })\n    t.list.field('pokemon', {\n      type: 'Pokemon',\n      args: {\n        name: stringArg(),\n      },\n      resolve: (parent, { name }, ctx) => {\n        return ctx.photon.pokemon.findMany({\n          where: {\n              name\n          }\n        })\n      },\n    })\n  },\n})\n\nconst Mutation = objectType({\n  name: 'Mutation',\n  definition(t) {\n    t.crud.createOnePokemon({ alias: 'addPokemon' })\n  },\n})\n\nconst Subscription = subscriptionField('newPokemon', {\n  type: 'Pokemon',\n  subscribe: (parent, args, ctx) => {\n    return ctx.photon.$subscribe.pokemon()\n  },\n  resolve: payload => payload\n})\n\nconst schema = makeSchema({\n  types: [Query, Mutation, Subscription, Pokemon, Attack, PokemonAttack, nexusPrisma],\n  outputs: {\n    schema: join(__dirname, '/schema.graphql')\n  },\n  typegenAutoConfig: {\n    sources: [\n      {\n        source: '@generated/photon',\n        alias: 'photon',\n      },\n    ],\n  },\n})\n\nconst server = new GraphQLServer({\n  schema,\n  context: request => {\n    return {\n      ...request,\n      photon,\n    }\n  },\n})\n\nserver.start(() => console.log(`🚀 Server ready at http://localhost:4000`))\n```\n\n```text\nimport { subscriptionField } from 'nexus';\nimport { idArg } from 'nexus/dist/core';\nimport { Context } from './types';\n\n export const PollResultSubscription = subscriptionField('pollResult', {\n  type: 'AnswerSubscriptionPayload',\n  args: {\n    pollId: idArg(),\n  },\n  subscribe(_: any, { pollId }: { pollId: string }, context: Context) {\n    // Subscribe to changes on answers in the given poll\n    return context.prisma.$subscribe.answer({\n      node: { poll: { id: pollId } },\n    });\n  },\n  resolve(payload: any) {\n    return payload;\n  },\n});\n```\n\n```text\nSubscription\n```\n\n```text\nSubscriptions\n```\n\n```text\nAnswerSubscriptionPayload\n```\n\n```text\nSubscription\n```\n\n========================================\n\nComments:\n- I thought I'll add the answer when the subscriptions are added but I'll add the edit as the answer :)\n- Ohh yeah I saw your issue on GitHub. I'm already subscribed to that issue. I think subscriptions only work right now with Pub/Sub model which is kinda hackish. And I talked with the team in Slack & they said it's not even specced out yet so we gotta wait. Until then no real-time :)\n- Yeah, I'm happy to fill the space with PubSub until they have something else going.","metadata":{"transformedAt":"2026-08-18T18:33:14.818Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":381,"estimatedTokens":2033}}58{"id":"stack-67412355","source":"stackoverflow","questionId":67412355,"title":"Can't make two 1:1 relations in one model in Prisma. Ambiguous relation detected","tags":["orm","schema","database-schema","prisma","prisma2"],"text":"Title: Can't make two 1:1 relations in one model in Prisma. Ambiguous relation detected\nTags: orm, schema, database-schema, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make two 1:1 relations in one model in Prisma ORM, but got following error:\n\nError validating model \"Person\": Ambiguous relation detected. The fields `placeOfBirth` and `placeOfDeath` in model `Person` both refer to `Place`. Please provide different relation names for them by adding `@relation()`.\n\nMy prisma schema:\n\n```\nmodel Place {\n id Int @id @default(autoincrement())\n name String\n persons Person[]\n}\n\nmodel Person {\n id Int @id @default(autoincrement())\n name String\n placeOfBirthId Int\n placeOfDeathId Int\n 👉 placeOfBirth Place @relation(fields: [placeOfBirthId], references: [id])\n placeOfDeath Place @relation(fields: [placeOfDeathId], references: [id])\n}\n```\n\nTotally don't get it.\n\n========================================\n\nCode:\n```text\nmodel Place {\n    id              Int     @id @default(autoincrement())\n    name            String\n    persons         Person[]\n}\n\nmodel Person {\n    id              Int     @id @default(autoincrement())\n    name            String\n    placeOfBirthId  Int\n    placeOfDeathId  Int\n 👉 placeOfBirth    Place   @relation(fields: [placeOfBirthId], references: [id])\n    placeOfDeath    Place   @relation(fields: [placeOfDeathId], references: [id])\n}\n```\n\n```text\nplaceOfBirth\n```\n\n```text\nplaceOfDeath\n```\n\n```text\nPerson\n```\n\n```text\nPlace\n```\n\n```text\n@relation(<name>)\n```\n\n```text\nmodel Place {\n  id     Int      @id @default(autoincrement())\n  name   String\n  Births Person[] @relation(\"Births\")\n  Deaths Person[] @relation(\"Deaths\")\n}\n\nmodel Person {\n  id             Int    @id @default(autoincrement())\n  name           String\n  placeOfBirthId Int\n  placeOfDeathId Int\n  placeOfBirth   Place  @relation(\"Births\", fields: [placeOfBirthId], references: [id])\n  placeOfDeath   Place  @relation(\"Deaths\", fields: [placeOfDeathId], references: [id])\n}\n```\n\n```text\nname\n```\n\n```text\nplaceOfBirth\n```\n\n```text\nplaceOfDeath\n```\n\n```text\nPlace\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":103,"estimatedTokens":521}}59{"id":"stack-61364113","source":"stackoverflow","questionId":61364113,"title":"Dockerfile: how to Download a file using curl and copy into the container","tags":["docker","docker-compose","dockerfile","prisma"],"text":"Title: Dockerfile: how to Download a file using curl and copy into the container\nTags: docker, docker-compose, dockerfile, prisma\nSource: Stack Overflow\n\nQuestion:\nin this example, I copy wait-for-it.sh inside /app/wait-for-it.sh\nBut, I don't want to save wait-for-it.sh in my local directory. I want to download it using curl and then copy into /app/wait-for-it.sh\n\n```\nFROM prismagraphql/prisma:1.34.8\nCOPY ./wait-for-it.sh /app/wait-for-it.sh\nRUN chmod +x /app/wait-for-it.sh\nENTRYPOINT [\"/bin/sh\",\"-c\",\"/app/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh\"]\n```\n\nWhat I have tried is this, but how can I get the `wait-for-it.sh` after downloading the file using curl command:\n\n```\nFROM prismagraphql/prisma:1.34.8\n\nFROM node:11-slim\n\nRUN apt-get update && apt-get install -yq build-essential dumb-init\n\nRUN curl -LJO https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh\n\nCOPY wait-for-it.sh /app/wait-for-it.sh\n\nRUN chmod +x /wait-for-it.sh\n\nENTRYPOINT [\"/bin/sh\",\"-c\",\"/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh\"]\n```\n\n========================================\n\nTop Answer:\nNot related but an easier way to handle downloads during build time is to use Docker's `ADD` directive without curl or wget.\n\n```\nADD https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /tmp\nCOPY /tmp/wait-for-it.sh /app/wait-for-it.sh\n```\n\nRight now, we recommend using Docker's ADD directive instead of running wget or curl in a RUN directive - Docker is able to handle the https URL when you use ADD, whereas your base image might not be able to use https, or might not even have wget or curl installed at all.\n\nhttps://github.com/just-containers/s6-overlay#usage\n\n========================================\n\nCode:\n```text\nFROM prismagraphql/prisma:1.34.8\nCOPY ./wait-for-it.sh /app/wait-for-it.sh\nRUN chmod +x /app/wait-for-it.sh\nENTRYPOINT [\"/bin/sh\",\"-c\",\"/app/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh\"]\n```\n\n```text\nFROM prismagraphql/prisma:1.34.8\n\nFROM node:11-slim\n\nRUN apt-get update && apt-get install -yq build-essential dumb-init\n\nRUN curl -LJO https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh\n\nCOPY wait-for-it.sh /app/wait-for-it.sh\n\nRUN chmod +x /wait-for-it.sh\n\nENTRYPOINT [\"/bin/sh\",\"-c\",\"/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh\"]\n```\n\n```text\nwait-for-it.sh\n```\n\n```text\nFROM prismagraphql/prisma:1.34.8\n\nRUN apk update && apk add build-base dumb-init curl\n\nRUN curl -LJO https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh\n\nRUN cp wait-for-it.sh /app/\n\nRUN chmod +x /wait-for-it.sh\n\nENTRYPOINT [\"/bin/sh\",\"-c\",\"/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh\"]\n```\n\n```text\n$ docker run --rm --entrypoint ls waitforit -l /app/\ntotal 36\ndrwxr-xr-x    1 root     root          4096 Aug 29  2019 bin\ndrwxr-xr-x    2 root     root         16384 Aug 29  2019 lib\n-rwxr-xr-x    1 root     root           462 Aug 29  2019 prerun_hook.sh\n-rwxr-xr-x    1 root     root            61 Aug 29  2019 start.sh\n-rw-r--r--    1 root     root          5224 Apr 22 13:46 wait-for-it.sh\n```\n\n```text\ncp\n```\n\n```text\n/app\n```\n\n```text\nADD https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /tmp\nCOPY /tmp/wait-for-it.sh /app/wait-for-it.sh\n```\n\n```text\nADD\n```\n\n========================================\n\nComments:\n- you can use `-o` flag in `curl` command\n- doesn't work. I mean after running the curl command where the file is stored? I want copy the stored file into /app/wait-for-it.sh\n- It's stored in the working directory. You can set the working directory with a `WORKDIR` before the `RUN curl`.\n- after running your solution, I am getting this /wait-for-it.sh: line 179: /app/start.sh: No such file or directory\n- @UnbearableLightness: `-O` (capital) automatically creates file with the name that's present in the URL after stripping the path. Had i been using `-o`, i would have specified the file name as well.\n- @Ashik: Are you sure you're using the above Dockerfile content while building the image? I'm able to see the files in both the `src` and `destination`. Check my updated answer. Nothing has been changed in the Dockerfile code i posted. Just try the command i've added and kindly paste the result.\n- Also, if i run `docker run --rm -it waitforit`, i get output: `wait-for-it.sh: waiting for mysql:3306 without a timeout`\n- I think problem is in the entrypoint line. It didn't find /app/start.sh but, you can see my first snippet I didn't create any folder called `app` using RUN command. I copied the `wait-for-it.sh` inside `&#47;app&#47;wait-for-it.sh` and it worked. but now I want to get the ./wait-for-it.sh by running curl command (I don't want to save wait-for-it.sh locally).\n- maybe I find the problem. I am using two images here, one is node and one is prisma-graphql. so, prisma containers /app directory is messed up with node containers app directory. but, I want to use Curl. thats why I have to import from node image. is there any other way to get curl without using node image?\n- With `-o`, you can put the downloaded file where you want it, no need to move it after fetching it. If you use `--create-dirs` it will create any missing directories in the path you specify.\n- I suggest to use `curl -LJOf` (adding option `-f` or `--fail`) to make `curl` fail the build if the file could not be downloaded. Makes it much easier to track down problems.\n- What it says is `ADD` instead of `RUN`, but the answer hasn't been updated\n- Nice catch! Approved the edit","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":134,"estimatedTokens":1391}}60{"id":"stack-69526209","source":"stackoverflow","questionId":69526209,"title":"Prisma how can I update only some of the models fields in update()","tags":["express","prisma"],"text":"Title: Prisma how can I update only some of the models fields in update()\nTags: express, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a Prisma model with lets say 10 fields.\nThink User model with firstname, lastname, address, e-mail , phone, mobile, age etc.\n\nI am trying to write a update method for this, where I most of the times only want to update some or only 1 of the fields. Not the whole User. If the field is not sent with the request, I want to keep the value from the db.\n\nWhat would the best practice be for this. Should I check for all fields to be in the req object?\nHow could I write this for prisma?\n\nExample on how I would like it to work:\n\n```\nreq = {firstname: 'Bob', email: 'bob@bob.bob', etc}\n\nconst updateUser = await prisma.user.update({\n where: {\n email: 'viola@prisma.io',\n },\n data: {\n req.firstname ? (email: req.firstname) : null,\n req.email ? (email: req.email) : null,\n req.address? (email: req.address) : null,\n },\n})\n```\n\nOr should I check for values to be present in req and build the data object in 10 versions:\n\n```\nlet customDataObject = {}\nif (req.firstname) {\n customDataObject.firstname = req.firstname\n}\nif (req.email) {\n customDataObject.email= req.email\n}\n\nconst updateUser = await prisma.user.update({\n where: {\n email: 'viola@prisma.io',\n },\n data: customDataObject,\n})\n```\n\n========================================\n\nTop Answer:\nExtending the previous answer, from **Prisma 6**, you can provide `Prisma.skip` if you want to skip a field if that field doesn't have any value. Then Prisma will ignore that field. If `undefined` is provided in Prisma 6, it will throw an error. Prisma made this change to prevent accidental deletions or updates.\n\nSo the updated query should be:\n\n```\nconst updateUser = await prisma.user.update({\n where: {\n email: 'viola@prisma.io',\n },\n data: {\n firstname: req.firstname ?? Prisma.skip,\n email: req.email ?? Prisma.skipd, \n address: req.address ?? Prisma.skip\n },\n})\n```\n\n========================================\n\nCode:\n```text\nreq = {firstname: 'Bob', email: 'bob@bob.bob', etc}\n\nconst updateUser = await prisma.user.update({\n  where: {\n    email: 'viola@prisma.io',\n  },\n  data: {\n    req.firstname ? (email: req.firstname) : null,\n    req.email ? (email: req.email) : null,\n    req.address? (email: req.address) : null,\n  },\n})\n```\n\n```text\nlet customDataObject = {}\nif (req.firstname) {\n   customDataObject.firstname = req.firstname\n}\nif (req.email) {\n   customDataObject.email= req.email\n}\n\nconst updateUser = await prisma.user.update({\n  where: {\n    email: 'viola@prisma.io',\n  },\n  data: customDataObject,\n})\n```\n\n```js\n// Assuming email, firstname and address fields exist in your prisma schema. \nconst updateUser = await prisma.user.update({\n  where: {\n    email: 'viola@prisma.io',\n  },\n  data: {\n    // If req.firstname is falsy, then return undefined, otherwise return it's value\n    firstname: req.firstname || undefined,\n    email: req.email || undefined, \n    address: req.address || undefined\n  },\n})\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n```text\nconst updateUser = await prisma.user.update({\n  where: {\n    email: 'viola@prisma.io',\n  },\n  data: {\n    firstname: req.firstname ?? Prisma.skip,\n    email: req.email ?? Prisma.skipd, \n    address: req.address ?? Prisma.skip\n  },\n})\n```\n\n```text\nPrisma.skip\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- The meaning of `undefined` has been changed in Prisma 6. Now you need to provide `Prisma.skip` instead of `undefined` if you want to skip a field.\n- And if you're not on prisma 6, you can just do `...(req.firstname && {firstname: req.firstname})`. This way it won't set the firstname to undefined if the user had a firstname before, but the update request omitted that field.","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":161,"estimatedTokens":954}}61{"id":"stack-65998680","source":"stackoverflow","questionId":65998680,"title":"prisma findUnique where takes only one unique argument","tags":["unique","prisma","prisma2"],"text":"Title: prisma findUnique where takes only one unique argument\nTags: unique, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI ran into an issue where I need to check if a user exists by his username and email since both are unique fields in the database, but I got an error.\n\nArgument where of type UserWhereUniqueInput needs exactly one argument, but you provided username and email. Please choose one.\n\nso, is there any way to execute this query just once? instead of running one for each like the following\n\n```\nconst user = await prisma.user.findUnique({\n where: {\n username,\n email,\n },\n});\n```\n\nand not like this\n\n```\nconst user = await prisma.user.findUnique({\n where: {\n username,\n },\n});\n\nconst user = await prisma.user.findUnique({\n where: {\n email,\n },\n});\n```\n\n========================================\n\nTop Answer:\nif you are looking for a unique value that would bring you a single result you can use findFirst as well. which would give you Object instead of Array. findMany returns an Array even though you are looking for a unique value.\n\n```\nconst users = await prisma.user.findFirst({\n where: {OR: [{username},{email}]}\n});\n```\n\n========================================\n\nCode:\n```js\nconst user = await prisma.user.findUnique({\n  where: {\n    username,\n    email,\n  },\n});\n```\n\n```js\nconst user = await prisma.user.findUnique({\n  where: {\n    username,\n  },\n});\n\nconst user = await prisma.user.findUnique({\n  where: {\n    email,\n  },\n});\n```\n\n```js\nconst query = await prisma.user.findUnique({\n  where: {\n    user: user.username\n  },\n  select: {\n    user: true,\n    email: true\n  }\n});\n```\n\n```text\nconst users = await prisma.user.findMany({\n       where: {\n        OR: [\n          {username},\n          {email}\n        ]\n      }\n  });\n if (users.length !== 0) {...}\n```\n\n```js\nconst users = await prisma.user.findFirst({\n  where: {OR: [{username},{email}]}\n});\n```\n\n```text\nconst user = await prisma.user.findUnique({\n        where: {\n          email\n        },\n      });\n```\n\n```text\nmodel user {\n  username : String\n  email    : String\n  @@unique([username, email])\n}\n```\n\n```text\nconst user = await prisma.findUnique({\n        where: {\n          username_email : { username, email },\n        },\n      });\n```\n\n```text\nconst customerSignIn = async (req, res) => {\n  const { email } = req.body\n  try {\n    const getUser = await customers.findUnique({\n      where: { email },\n      select: {\n        email: true,\n        password: true,\n      },\n    }) || null\n    console.log(getUser)\n    const compare = await comparePassword(req.body.password, getUser.password)\n    console.log(compare)\n    // getUser && getUser.password === req.body.password ? ....\n    getUser && compare ? res.json({....\n```\n\n```text\nconst { email, password } = req.body\n```\n\n========================================\n\nComments:\n- Are both `username` and `email` required on your `User` model or is one of them marked as optional with a `?` in the Prisma schema?\n- Nikolas from the Prisma team here. I don't think the `select` makes a difference but this is key: \"I am not sure exactly why you would select user + email as both unique, as I would assume that one is tied to the other anyhow.\" Since both `id` and `email` are already unique properties, it doesn't make any sense to provide both in a `findUnique` query. @ahmdtalat you should be able to just use one of them and get the same result.\n- I still don't know why this won't work for me. I am doing exactly this and I get \"PrismaClientValidationError\". I tried chatgpt, bard, google, no one seems to have solution to why this doesn't work.\n- I agree that logically we should all have unique emails, unless we're talking about company. Let's say you work at xy and your name is John Doe. You get fired and your email is destroyed or whatever. Then another John Doe comes and gets the same email. This can also work for goverments, etc. So, email uniqueness is out of the window 😁 (I am working right now on a project that will have that problem).\n- @Korovjov query by the unique id then.\n- what if we need an either situation, email or name, where email and name are both nullable but atleast one is present","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":158,"estimatedTokens":1040}}62{"id":"stack-73866587","source":"stackoverflow","questionId":73866587,"title":"prisma Error: p1001: Can't reach database server at `db.xocheossqzkirwnhzxxm.supabase.co`:`5432`","tags":["postgresql","next.js","prisma","supabase-database"],"text":"Title: prisma Error: p1001: Can't reach database server at `db.xocheossqzkirwnhzxxm.supabase.co`:`5432`\nTags: postgresql, next.js, prisma, supabase-database\nSource: Stack Overflow\n\nQuestion:\nI started learning about prisma and supabase and would like to implement both technologies in my Next.js app. After running `npx prisma migrate dev --name init` I was faced with the following error:\n\n```\nEnvironment variables loaded from .env \nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\": PostgreSQL database \"postgres\", schema \"public\" at \"db.xocheossqzkirwnhzxxm.supabase.co:5432\"\n\nError: P1001: Can't reach database server at `db.xocheossqzkirwnhzxxm.supabase.co`:`5432`\n\nPlease make sure your database server is running at `db.xocheossqzkirwnhzxxm.supabase.co`:`5432`.\n```\n\nmy password to the db does not contain any special characters here is my schema.prisma file:\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel Home{\n id String @id @default(cuid())\n image String?\n title String\n description String\n price Float\n guests Int\n beds Int\n baths Int\n createdAt DateTime @default(now())\n updateAt DateTime @updatedAt\n}\n```\n\nhere is my .env:\n\n```\nDATABASE_URL=\"postgresql://postgres:[YOUR-PASSWORD]@db.xocheossqzkirwnhzxxm.supabase.co:5432/postgres\"\n```\n\n========================================\n\nTop Answer:\nIf you're on an IPv4 network, you can use the option meant for connecting to IPv4 networks under \"Connect\". I was able to get around this error after I switched to the `Session Spooler` connection settings\n\nhttps://i.sstatic.net/2yNjgDM6.png\n\n========================================\n\nCode:\n```text\nEnvironment variables loaded from .env                                                                                                                                            \nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\": PostgreSQL database \"postgres\", schema \"public\" at \"db.xocheossqzkirwnhzxxm.supabase.co:5432\"\n\nError: P1001: Can't reach database server at `db.xocheossqzkirwnhzxxm.supabase.co`:`5432`\n\nPlease make sure your database server is running at `db.xocheossqzkirwnhzxxm.supabase.co`:`5432`.\n```\n\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Home{\n  id        String @id @default(cuid())\n  image     String?\n  title     String\n  description String\n  price     Float\n  guests    Int\n  beds      Int\n  baths     Int\n  createdAt DateTime @default(now())\n  updateAt  DateTime @updatedAt\n}\n```\n\n```text\nDATABASE_URL=\"postgresql://postgres:[YOUR-PASSWORD]@db.xocheossqzkirwnhzxxm.supabase.co:5432/postgres\"\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n```text\nconnect_timeout=300\n```\n\n```text\nmysql://USER:PASSWORD@HOST:PORT/DATABASE\n```\n\n```text\nDATABASE_URL=\"mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?*ssl={\"rejectUnauthorized\":true}*\"\n```\n\n```text\nDATABASE_URL=\"mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict\"\n```\n\n```text\nnpx prisma db push\n```\n\n```text\nnpx prisma migrate dev --preview-feature\n```\n\n```text\nrelationMode = \"prisma\"\n```\n\n```text\nschema.prisma\n```\n\n```text\npgbouncer=true\n```\n\n```text\nDATABASE_URL='postgresql://xxxxxxx:xxxxxxxx@xxxxxxx.xxx.xxx.neon.tech/xxxxxxx?sslmode=require&pgbouncer=true'\n```\n\n```js\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n```text\nDATABASE_URL\n```\n\n```text\nDATABASE_URL\n```\n\n```text\npostgres://[USER]:[YOUR-PASSWORD]@aws-0-eu-west-1.pooler.supabase.com:5432/postgres\n```\n\n```text\nDATABASE_URL=\"mysql://root:Thi%24P%40ssword@localhost:3306/database\"\n```\n\n```text\n.env\n```\n\n```text\nDATABASE_URL=\"postgresql://[user]:[password]@[neon_hostname]/[dbname]?sslmode=require&connect_timeout=60\"\n```\n\n```text\nSession Spooler\n```\n\n```text\nDATABASE_URL=\"postgresql://postgres:[YOUR_USER]@[YOUR_PSSWRD]:5432/[DB_NAME]?schema=public\"\n```\n\n```text\ndocker exec -it properties-ms sh\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n```text\nsudo nano /etc/hosts\n```\n\n```text\n127.0.0.1       postgres\n```\n\n```text\nCtrl+O, Enter, Ctrl+X\n```\n\n```text\nDATABASE_URL=\"postgresql://postgres.nophpwrgiuudtnsxtyiv:[password]@aws-1-us-east-2.pooler.supabase.com:5432/postgres?sslmode=require\"\n```\n\n========================================\n\nComments:\n- With a `can't reach` error like this, your username and password never came into play. Something prevented prisma from getting access to your PostgreSQL server over the network. Maybe there's a firewall in the way. Maybe PostgreSQL is using a different port. Maybe it isn't running at all.\n- Turning off my firewall didn't work @O.Jones\n- I experienced the same issue, but the cause was different. Looks like supabase will ban your IP address if you fail to connect multiple times (in my case, with invalid password, I guess). You can see it in supabase under `Project Settings > Database > Network Bans`. Hope this will help someone as I only noticed the section in settings by accident.\n- I have the same exact issue. Adding the connection_timeout sadly didn't help still timed out. It works if I connect using the cli mysql or pscale but if I try to access it through Prisma is just fails for some reason. Super weird, still haven't found a solution. Seems the common factor is Prisma + PlanetScale?\n- chat gpt never guessed this one\n- this is the solution if any one happen just use hotspot try and try you will pass then PS C:\\Users\\user\\Desktop\\workspace\\quran> pnpm prisma db push Loaded Prisma config from prisma.config.ts. Prisma schema loaded from prisma\\schema.prisma. Datasource \"db\": PostgreSQL database \"postgres\", schema \"public\" at \"aws-0-eu-west-1.pooler.supabase.com:5432\" Error: P1001: Can't reach database server at `aws-0-eu-west-1.pooler.supabase.com:5432` Please make sure your database server is running at `aws-0-eu-west-1.pooler.supabase.com:5432`. PS C:\\Users\\user\\Desktop\\workspace\\quran>\n- this worked for me, didn't know that it affects db connection. I'm using proton for scraping ip blocked website\n- I love u <3 <3 <3\n- Thank you so much. This solution worked for me.\n- Use Session Pooler instead of direct connect.\n- That worked for me too!\n- Thank you very much\n- Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including at least one that has been validated by the community. **It would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.** Can you kindly edit your answer to offer an explanation?\n- merci pour votre reponse","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":227,"estimatedTokens":1744}}63{"id":"stack-72746602","source":"stackoverflow","questionId":72746602,"title":"Prisma.io long text with mysql","tags":["mysql","prisma"],"text":"Title: Prisma.io long text with mysql\nTags: mysql, prisma\nSource: Stack Overflow\n\nQuestion:\nI want an alternative for long `Text` type in **MySql** with Prisma\n\n`error: Type \"TEXT\" is neither a built-in type, nor refers to another model, custom type, or enum.`\n\nI see Only String\n\n========================================\n\nCode:\n```text\nText\n```\n\n```text\nerror: Type \"TEXT\" is neither a built-in type, nor refers to another model, custom type, or enum.\n```\n\n```text\nfield String @db.Text\n```\n\n```text\nString\n```\n\n```text\n@db.Text\n```\n\n```text\n@db.LongText\n```\n\n```text\nvarchar(191)\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":41,"estimatedTokens":147}}64{"id":"stack-68761366","source":"stackoverflow","questionId":68761366,"title":"LEFT JOINS and aggregation in a single Prisma query","tags":["mysql","node.js","prisma","prisma2"],"text":"Title: LEFT JOINS and aggregation in a single Prisma query\nTags: mysql, node.js, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have a database with multiple tables that frequently need to be queried with `LEFT JOIN` so that results contain aggregated data from other tables. Snippet from my Prisma schema:\n\n```\nmodel posts {\n id Int @id @unique @default(autoincrement())\n user_id Int\n movie_id Int @unique\n title String @db.Text\n description String? @db.Text\n tags Json?\n created_at DateTime @default(now()) @db.DateTime(0)\n image String? @default(\"https://picsum.photos/400/600/?blur=10\") @db.VarChar(256)\n year Int\n submitted_by String @db.Text\n tmdb_rating Decimal? @default(0.0) @db.Decimal(3, 1)\n tmdb_rating_count Int? @default(0)\n}\n\nmodel ratings {\n id Int @unique @default(autoincrement()) @db.UnsignedInt\n entry_id Int @db.UnsignedInt\n user_id Int @db.UnsignedInt\n rating Int @default(0) @db.UnsignedTinyInt\n created_at DateTime @default(now()) @db.DateTime(0)\n updated_at DateTime? @db.DateTime(0)\n\n @@id([entry_id, user_id])\n}\n```\n\nIf I wanted to return the average rating when querying `posts`, I could use a query like:\n\n```\nSELECT \n p.*, ROUND(AVG(rt.rating), 1) AS user_rating\nFROM\n posts AS p\n LEFT JOIN\n ratings AS rt ON rt.entry_id = p.id\nGROUP BY p.id;\n```\n\nI'm not exactly sure how/whether I can achieve something similar with Prisma, because as it stands right now, it seems like this would require two separate queries, which isn't optimal because there is sometimes the need for 2 or 3 joins or `SELECT`s from other tables.\n\nHow can I make a query/model/something in Prisma to achieve the above?\n\n========================================\n\nTop Answer:\nDespite the accepted answer, the actual answer is: No.\n\nFor actual performant joins to work, they must solve an issue that's been open for about a year and a half as of writing this response: https://github.com/prisma/prisma/issues/5184\n\nCurrently, there is no way to join tables together. Queries that include relations only include the relational data by using separate queries.\n\n========================================\n\nCode:\n```text\nmodel posts {\n  id                Int      @id @unique @default(autoincrement())\n  user_id           Int\n  movie_id          Int      @unique\n  title             String   @db.Text\n  description       String?  @db.Text\n  tags              Json?\n  created_at        DateTime @default(now()) @db.DateTime(0)\n  image             String?  @default(\"https://picsum.photos/400/600/?blur=10\") @db.VarChar(256)\n  year              Int\n  submitted_by      String   @db.Text\n  tmdb_rating       Decimal? @default(0.0) @db.Decimal(3, 1)\n  tmdb_rating_count Int?     @default(0)\n}\n\nmodel ratings {\n  id         Int       @unique @default(autoincrement()) @db.UnsignedInt\n  entry_id   Int       @db.UnsignedInt\n  user_id    Int       @db.UnsignedInt\n  rating     Int       @default(0) @db.UnsignedTinyInt\n  created_at DateTime  @default(now()) @db.DateTime(0)\n  updated_at DateTime? @db.DateTime(0)\n\n  @@id([entry_id, user_id])\n}\n```\n\n```text\nSELECT \n    p.*, ROUND(AVG(rt.rating), 1) AS user_rating\nFROM\n    posts AS p\n        LEFT JOIN\n    ratings AS rt ON rt.entry_id = p.id\nGROUP BY p.id;\n```\n\n```text\nLEFT JOIN\n```\n\n```text\nposts\n```\n\n```text\nSELECT\n```\n\n```text\nmodel Post {\n  id              Int      @id @unique @default(autoincrement()) @map(\"id\")\n  userId          Int      @map(\"user_id\")\n  movieId         Int      @unique @map(\"movie_id\")\n  title           String   @map(\"title\") @db.Text\n  description     String?  @map(\"description\") @db.Text\n  tags            Json?    @map(\"tags\")\n  createdAt       DateTime @default(now()) @map(\"created_at\") @db.DateTime(0)\n  image           String?  @default(\"https://picsum.photos/400/600/?blur=10\") @map(\"image\") @db.VarChar(256)\n  year            Int      @map(\"year\")\n  submittedBy     String   @map(\"submitted_by\") @db.Text\n  tmdbRating      Decimal? @default(0.0) @map(\"tmdb_rating\") @db.Decimal(3, 1)\n  tmdbRatingCount Int?     @default(0) @map(\"tmdb_rating_count\")\n  ratings         Rating[]\n\n  @@map(\"posts\")\n}\n\nmodel Rating {\n  id        Int       @unique @default(autoincrement()) @map(\"id\") @db.UnsignedInt\n  userId    Int       @map(\"user_id\") @db.UnsignedInt\n  rating    Int       @default(0) @map(\"rating\") @db.UnsignedTinyInt\n  entryId   Int\n  entry     Post      @relation(fields: [entryId], references: [id])\n  createdAt DateTime  @default(now()) @map(\"created_a\") @db.DateTime(0)\n  updatedAt DateTime? @map(\"updated_a\") @db.DateTime(0)\n\n  @@id([entryId, userId])\n  @@map(\"ratings\")\n}\n```\n\n```text\n// All posts with ratings data\n    const postsWithRatings = await prisma.post.findMany({\n        include: {\n            // Here you can keep including data from other models\n            ratings: true\n        },\n        // you can also \"select\" specific properties\n    });\n\n    // Calculate on your API\n    const ratedPosts = postsWithRatings.map( post => {\n        const ratingsCount = post.ratings.length;\n        const ratingsTotal = post.ratings.reduce((acc, b) => acc + b.rating, 0)\n        return {\n            ...post,\n            userRating: ratingsTotal / ratingsCount\n        }\n    })\n\n    // OR...\n\n\n    // Get avg from db\n    const averages = await prisma.rating.groupBy({\n        by: [\"entryId\"],\n        _avg: {\n            rating: true\n        },\n        orderBy: {\n            entryId: \"desc\"\n        }\n    })\n    //  Get just posts\n    const posts = await prisma.post.findMany({\n        orderBy: {\n            id: \"desc\"\n        }\n    });\n    // then match the ratings with posts\n    const mappedRatings = posts.map( (post, idx) => {\n        return {\n            ...post,\n            userRating: averages[idx]._avg.rating\n        }\n    })\n```\n\n========================================\n\nComments:\n- I think the question is hoping to literally solve the problem, as in generate 1 SQL statement that does both. Two queries \"works\" but isn't a solution.\n- This is no longer accurate as of Feb '24: prisma.io/blog/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":199,"estimatedTokens":1502}}65{"id":"stack-71850295","source":"stackoverflow","questionId":71850295,"title":"Prisma Types Between Microservices","tags":["node.js","typescript","express","microservices","prisma"],"text":"Title: Prisma Types Between Microservices\nTags: node.js, typescript, express, microservices, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm working on a project right now that has multiple TypeScript microservices performing operations on the same database. In each microservice, we are using the Prisma client to perform database operations. The issue I'm experiencing is we need to duplicate our `schema.prisma` file in each microservice and generate the Prisma client for each service. Is there a way to manage our database in a separate project while sharing the generated client between the microservices **without** having duplicate `schema.prisma` in each project?\n\n========================================\n\nTop Answer:\n### Updated Answer from the Author\n\nThe way we handled it is using the `assets` block, which enables copying generated assets into every micro service which wants to the schema in the project.json which needs the dependency. This is a MonoRepo of course - e.g.\n\n```\n\"assets\": [\n {\n \"input\": \"libs/prisma/luca/\",\n \"output\": \"otherlocation/schema.prisma\",\n \"glob\": \"**/schema.prisma\",\n \"ignore\": []\n },\n]```\n```\n\n========================================\n\nCode:\n```text\nschema.prisma\n```\n\n```text\nschema.prisma\n```\n\n```text\n\"assets\": [\n  {\n    \"input\": \"libs/prisma/luca/\",\n    \"output\": \"otherlocation/schema.prisma\",\n    \"glob\": \"**/schema.prisma\",\n    \"ignore\": []\n  },\n]```\n```\n\n```text\nassets\n```\n\n========================================\n\nComments:\n- That article provided is not quite sufficient. We followed exact steps and when the library is imported, the construction of the LucaClient (for use within the suggested ctx) immediately throws an error because its not looking in the library for the schema. Its looking for it at Runtime from the Runtime current directory. Seeing as how both the client AND schema are generated, it should not be necessary to LOAD the schema file at all, and certainly not from some arbitrary runtime directory. The design did not consider sharing `PrismaClient` across deployables as a \"first class citizen\"\n- Hi, did you find any workaround ? I am facing the same issue with prisma.\n- @Decoded any luck with a solution for sharing PrismaClient and Prisma?\n- @Decoded also looking for a solution, spent the last 48 hours trying to create a private NPM package. Why is this so hard? It should be a common task most people are trying to do...\n- @Leafyshark I've updated the answer to reflect our solution. It works well, and we don't have to remember to do the copying manually\n- Could you please elaborate? I'm sorry this is hard to understand for me.","metadata":{"transformedAt":"2026-08-18T18:33:14.819Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":60,"estimatedTokens":654}}66{"id":"stack-69850598","source":"stackoverflow","questionId":69850598,"title":"How to resolve this typescript error on global node.js object","tags":["node.js","typescript","postgresql","next.js","prisma"],"text":"Title: How to resolve this typescript error on global node.js object\nTags: node.js, typescript, postgresql, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am following this guide https://vercel.com/guides/nextjs-prisma-postgres to create a full stack app. Typescript is throwing an error in this snippet of code:\n\n```\nimport { PrismaClient } from '@prisma/client';\nlet prisma: PrismaClient;\n\nif (process.env.NODE_ENV === 'production') {\n prisma = new PrismaClient();\n} else {\n if (!global.prisma) {\n global.prisma = new PrismaClient();\n }\n prisma = global.prisma;\n}\n\nexport default prisma;\n```\n\nTypeScript is throwing a `ts7017` on the `global.prisma`:\n\n```\nElement implicitly has an 'any' type because type 'typeof globalThis' has no index signature.\n```\n\nCan someone help me understand this and how to fix? I set 'strict' to false in the tsconfig for the meantime and that supressed the issue for the meantime, though I'm sure having it off defeats the purpose of TS.\n\n========================================\n\nTop Answer:\nAccording to the docs you need to declare the variable `global` first:\n\n```\nimport { PrismaClient } from '@prisma/client'\n\ndeclare global {\n var prisma: PrismaClient | undefined\n}\n\nexport const prisma =\n global.prisma ||\n new PrismaClient({\n log: ['query'],\n });\n\nif (process.env.NODE_ENV !== 'production') global.prisma = prisma;\n```\n\nYou can also have a separate file `globals.d.ts` with the declaration in it.\n\n========================================\n\nCode:\n```text\nimport { PrismaClient } from '@prisma/client';\nlet prisma: PrismaClient;\n\nif (process.env.NODE_ENV === 'production') {\n  prisma = new PrismaClient();\n} else {\n  if (!global.prisma) {\n    global.prisma = new PrismaClient();\n  }\n  prisma = global.prisma;\n}\n\nexport default prisma;\n```\n\n```text\nElement implicitly has an 'any' type because type 'typeof globalThis' has no index signature.\n```\n\n```text\nts7017\n```\n\n```text\nglobal.prisma\n```\n\n```text\ndeclare global {\n  var prisma: PrismaClient; // This must be a `var` and not a `let / const`\n}\n\nimport { PrismaClient } from \"@prisma/client\";\nlet prisma: PrismaClient;\n\nif (process.env.NODE_ENV === \"production\") {\n  prisma = new PrismaClient();\n} else {\n  if (!global.prisma) {\n    global.prisma = new PrismaClient();\n  }\n  prisma = global.prisma;\n}\n\nexport default prisma;\n```\n\n```text\n@types/node\n```\n\n```text\nimport { PrismaClient } from '@prisma/client'\n\ndeclare global {\n  var prisma: PrismaClient | undefined\n}\n\nexport const prisma =\n  global.prisma ||\n  new PrismaClient({\n    log: ['query'],\n  });\n\nif (process.env.NODE_ENV !== 'production') global.prisma = prisma;\n```\n\n```text\nglobal\n```\n\n```text\nglobals.d.ts\n```\n\n========================================\n\nComments:\n- Do you know how `global.prisma` is declared? If you don't have access to its declaration, have you tried casting it with `global.prisma as PrismaClient`?\n- I would just not use the global.. It's not even clear why there doing that in the first place.. strange!!! They even import later. `import prisma from '..&#47;lib&#47;prisma';`\n- Nikolas from the Prisma team here! We recommend the instantiation of `PrismaClient` in this way because otherwise the DB connection limit gets exhausted in development due to Next.js' hot reloading. Here's our docs page about this: prisma.io/docs/support/help-articles/&hellip; I'm checking back with some of our TypeScript engineers to see how this issue can be solved.\n- Can you explain a little more the purpose of writing the | undefined ?\n- The pipe in this case is used to separate the different types the variable *prisma* can potentially be. By adding ‘| undefined’ typescript will warn if the variable is used without checking if it’s defined.\n- thanks for the clarification and helping me understand :)\n- i was trying the same but i was adding const instead of let. i am confused why it didnt worked with const?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":144,"estimatedTokens":1031}}67{"id":"stack-71604148","source":"stackoverflow","questionId":71604148,"title":"Is it possible to efficiently change table and column names, using prisma?","tags":["postgresql","prisma"],"text":"Title: Is it possible to efficiently change table and column names, using prisma?\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to use prisma on an existing database. Now that I'm researching it, I realise that all my tables and columns are incorrectly named. I would like to correct the names, but I don't want to lose my data.\n\nI did a prisma \"pull\" so I have a schema of my current database. But then I don't quite understand how (if possible) do I rename my tables and columns using the schema.\n\nWhat are my options? Can I change the schema.prisma and make prisma take care of all the \"alter\" statements? How do I do this?\n\n========================================\n\nTop Answer:\nAnother solution for changing column names and table names is the following:\n\n- Change the column/table name in SQL\n\n- Now change the column/table name in your schema.prisma to the same name you changed it in SQL\n\n- Run npx prisma db pull\n\nOnce the 3rd step runs successfully, your column name has been changed in prisma.\n\n========================================\n\nCode:\n```text\nprisma migrate dev --create-only\n```\n\n```text\nschema.prisma\n```\n\n```text\nprisma migrate dev\n```\n\n========================================\n\nComments:\n- I don't know prisma, but in \"plain SQL\", you can do a simple `alter table ... rename to ...` or `alter table ... rename column ... to ...` See the manual for details.\n- I appreciate you trying to help, but the question was regarding prisma specifically. The idea was that I shouldn't have to write these \"alter table\" statements manually, prisma would take care of it. But it seems I do have to write them manually after all.\n- Do i need additional commands for index? e.g. `@unique`\n- Thank you, still needed in late 2023. Though i needed 'yarn' before the command.","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":46,"estimatedTokens":450}}68{"id":"stack-72440256","source":"stackoverflow","questionId":72440256,"title":"How do I perform a count on a relation with a where clause in prisma?","tags":["prisma"],"text":"Title: How do I perform a count on a relation with a where clause in prisma?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI have the following query which gives all posts and a count of all comments. Now I'd like to get a count of all comments with the post that have the approved field set to true. I can't seem to figure this out.\n\n```\nprisma.post.findMany({\n include: {\n _count: { select: { Comment: true } },\n },\n });\n```\n\nThanks for any help.\n\n========================================\n\nTop Answer:\nAvailable since 4.3.0.\n\nenable in your schema file:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"filteredRelationCount\"] and then query:\n\n```\nawait prisma.post.findMany({\n select: {\n _count: {\n select: {\n comment: { where: { approved: true } },\n },\n },\n },\n})\n```\n\n========================================\n\nCode:\n```text\nprisma.post.findMany({\n    include: {\n      _count: { select: { Comment: true } },\n    },\n  });\n```\n\n```text\n_count\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"filteredRelationCount\"] << add this \n}\n```\n\n```text\nawait prisma.post.findMany({\n  select: {\n    _count: {\n      select: {\n        comment: { where: { approved: true } },\n      },\n    },\n  },\n})\n```\n\n========================================\n\nComments:\n- You can put the condition in the where clause. I think you still want to return all records though and want just the count of it. In that case you can go ahead with the accepted answer.\n- What if I want to get only those whose quantity is a certain number? Following the case, the post with 4 comments, for example.","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":80,"estimatedTokens":409}}69{"id":"stack-65587200","source":"stackoverflow","questionId":65587200,"title":"Updating a many-to-many relationship in Prisma","tags":["prisma"],"text":"Title: Updating a many-to-many relationship in Prisma\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to figure out the right way to implement an upsert/update of the following schema:\n\n```\nmodel Post {\n author String @Id\n lastUpdated DateTime @default(now())\n categories Category[]\n}\n\nmodel Category {\n id Int @id\n posts Post[]\n}\n```\n\nHere is what I'd like to do. Get a post with category ids attached to it and insert it into the schema above.\n\nThe following command appears to insert the post\n\n```\nconst post = await prisma.post.upsert({\n where:{\n author: 'TK'\n },\n update:{\n lastUpdated: new Date()\n },\n create: {\n author: 'TK'\n }\n})\n```\n\nMy challenge is how do I also upsert the Category. I'll be getting a list of Catogories in the like 1,2,3 and if they do not exist I need to insert it into the category table and add the post to it. If the category does exist, I need to update the record with the post I inserted above preserving all attached posts.\n\nWould appreciate it if I could be pointed in the right direction.\n\n========================================\n\nCode:\n```prisma\nmodel Post {\n  author      String     @Id\n  lastUpdated DateTime   @default(now())\n  categories  Category[]\n}\n\nmodel Category {\n  id     Int     @id\n  posts  Post[]\n}\n```\n\n```js\nconst post = await prisma.post.upsert({\n  where:{\n    author: 'TK'\n  },\n  update:{\n    lastUpdated: new Date()\n  },\n  create: {\n    author: 'TK'\n  }\n})\n```\n\n```text\nmodel Post {\n  author      String     @id\n  lastUpdated DateTime   @updatedAt\n  categories  Category[]\n}\n\nmodel Category {\n  id    Int    @id\n  posts Post[]\n}\n```\n\n```js\nconst categories = [\n  { create: { id: 1 }, where: { id: 1 } },\n  { create: { id: 2 }, where: { id: 2 } },\n]\nawait db.post.upsert({\n  where: { author: 'author' },\n  create: {\n    author: 'author',\n    categories: {\n      connectOrCreate: categories,\n    },\n  },\n  update: {\n    categories: { connectOrCreate: categories },\n  },\n})\n```\n\n```text\n@updatedAt\n```\n\n========================================\n\nComments:\n- Thanks for your answer. That code works, however, when I do an upsert with the same categoeries but a different author, a findMany() query will throw a panic. const posts = await prisma.post.findMany( {include: {categories:true}}); Using prisma studio to query the post table will also fail because of this. I'm trying to understand what is causing the failure but its not readily apparent to me.\n- Had to modify the Category table with an additional field: `lastUpdated DateTime @updatedAt` to get this to work. Seems like you need another field for the findMany() query to work in a many to many relationship","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":113,"estimatedTokens":659}}70{"id":"stack-72197774","source":"stackoverflow","questionId":72197774,"title":"How to call \"where\" clause conditionally? prisma","tags":["prisma"],"text":"Title: How to call \"where\" clause conditionally? prisma\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nhow to filter record conditionally in prisma? For example, I have variable `sortByYear` that could contain either `undefined` or `integer`.\n\nI just want to ask if there are any ways to refactor the implementation below. I have tried looking to their documentation but I can't find one.\n\n```\nlet result = [];\n\nif (sortByYear) {\n result = await prisma.project.findMany({\n where: { provider_id: 50 }\n })\n} else {\n result = await prisma.project.findMany() \n}\n```\n\nIn laravel we can refactor this by using `when` clause that checks a variable first before executing the query. laravel when-clause\n\n========================================\n\nCode:\n```text\nlet result = [];\n\nif (sortByYear) {\n    result = await prisma.project.findMany({\n        where: { provider_id: 50 }\n    })\n} else {\n    result = await prisma.project.findMany()    \n}\n```\n\n```text\nsortByYear\n```\n\n```text\nundefined\n```\n\n```text\ninteger\n```\n\n```text\nwhen\n```\n\n```text\nconst result = await prisma.project.findMany({\n  where: {\n    ...(sortByYear ? { provider_id: 50 } : {}),\n  },\n});\n```\n\n========================================\n\nComments:\n- nvm. i figured it out for multiple operator. thanks!\n- If you user the `OR` operator, one of your conditions must be truthy to return any results: prisma.io/docs/reference/api-reference/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":67,"estimatedTokens":351}}71{"id":"stack-71942079","source":"stackoverflow","questionId":71942079,"title":"Error: Type 'number' is not assignable to type 'Decimal'","tags":["prisma"],"text":"Title: Error: Type 'number' is not assignable to type 'Decimal'\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI want to manually create an object of my Prisma schema\n\n```\nconst order: Order = {\n id: '1',\n name: 'Name',\n price: 99\n}\n\n...\n\n// Somewhere in autogenerated file by Prisma\nexport type Order = {\n id: string\n name: string\n price: Prisma.Decimal\n}\n```\n\nBut it throws an error\n\n```\nType 'number' is not assignable to type 'Decimal'.\n```\n\nHow to convert javascript `number` to Prisma `Decimal` type?\n\n========================================\n\nTop Answer:\nAlternatively, you can just make the number a string first:\n\n`new Decimal(`${expectedOutAmount}`)`\n\n========================================\n\nCode:\n```js\nconst order: Order = {\n  id: '1',\n  name: 'Name',\n  price: 99\n}\n\n...\n\n// Somewhere in autogenerated file by Prisma\nexport type Order = {\n  id: string\n  name: string\n  price: Prisma.Decimal\n}\n```\n\n```text\nType 'number' is not assignable to type 'Decimal'.\n```\n\n```text\nnumber\n```\n\n```text\nDecimal\n```\n\n```js\nimport { Prisma } from '@prisma/client'\n\nconst order: Order = {\n  id: '1',\n  name: 'Name',\n  price: new Prisma.Decimal(99)\n}\n```\n\n```text\nPrisma.Decimal\n```\n\n```text\nnew Decimal(`${expectedOutAmount}`)\n```\n\n========================================\n\nComments:\n- strange, using just like this I am having the error: \"Property 'd' is optional in type 'DeepPartialObject' but required in type 'Decimal'\" Schema: `value Decimal @db.Decimal(6, 2)`","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":93,"estimatedTokens":366}}72{"id":"stack-69228236","source":"stackoverflow","questionId":69228236,"title":"Prisma: Error querying the database: db error: FATAL: too many connections","tags":["next.js","prisma"],"text":"Title: Prisma: Error querying the database: db error: FATAL: too many connections\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using Prisma as ORM in my nextjs app. I am initiating the Prisma client in a lib file and importing the same where ever i need the instance. But still am getting the following error.\n\nError querying the database: db error: FATAL: too many connections for\nrole \"qcjoaamjgbnxjx\"\n\nprisma-client:\n\n```\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\nexport default prisma;\n```\n\n========================================\n\nTop Answer:\nI got the same error in my local computer. but my error was due to I have opened too many panels in pgAdmin. my database is Postgres. after removing all panels. my issue is solved\n\n========================================\n\nCode:\n```text\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\nexport default prisma;\n```\n\n```text\nPrismaClient\n```\n\n========================================\n\nComments:\n- So this was helpful, but I have a certain API endpoint that needs to run many queries. Whenever this endpoint is hit, the 20/20 connections gets maxed out. I'm not sure why though, as I created a global Prisma client. Do I need to just upgrade so I have many more than 20 connections? I feel that there must be some optimizing I can do, but I'm not sure exactly how.","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":42,"estimatedTokens":350}}73{"id":"stack-63349984","source":"stackoverflow","questionId":63349984,"title":"Cannot return null for non-nullable field , Debugger dosen't show null","tags":["graphql","apollo","prisma"],"text":"Title: Cannot return null for non-nullable field , Debugger dosen't show null\nTags: graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI have this schema.graphql\n\n```\n### This file was generated by Nexus Schema\n### Do not make changes to this file directly\n\ntype AuthPayload {\n token: String!\n users: users!\n}\n\nscalar DateTime\n\ntype Mutation {\n login(email: String, password: String): AuthPayload!\n signup(CREATED_BY: String, EMAIL: String, FIRST_NAME: String, IS_ACTIVE: Boolean, PASSWORD: String, USERNAME: String): AuthPayload!\n}\n\ntype Query {\n me: users\n}\n\ntype users {\n CREATED_BY: String!\n CREATED_ON: DateTime\n EMAIL: String!\n FIRST_NAME: String!\n id: Int!\n IS_ACTIVE: Boolean!\n LAST_NAME: String\n MODIFIED_BY: String\n MODIFIED_ON: DateTime\n ORGANIZATION_ID: String\n PASSWORD: String!\n PHONE: String\n USERNAME: String!\n}\n```\n\nmutations :-\n\n```\nconst Mutation = mutationType({\n definition(t) {\n t.field('signup', {\n type: 'AuthPayload',\n args: {\n FIRST_NAME: stringArg({ nullable: true }),\n EMAIL: stringArg(),\n PASSWORD: stringArg(),\n IS_ACTIVE: booleanArg(),\n USERNAME: stringArg(),\n CREATED_BY: stringArg(),\n },\n resolve: async (parent, { FIRST_NAME, EMAIL, PASSWORD ,IS_ACTIVE ,USERNAME,CREATED_BY }, ctx) => {\n const hashedPassword = await hash(PASSWORD, 10)\n\n const user = await ctx.prisma.users.create({\n data: {\n FIRST_NAME,\n EMAIL,\n PASSWORD: hashedPassword,\n IS_ACTIVE,\n USERNAME,\n CREATED_BY\n },\n })\n return {\n token: sign({ userId: user.id }, APP_SECRET),\n user,\n }\n },\n })\n\n t.field('login', {\n type: 'AuthPayload',\n args: {\n email: stringArg(),\n password: stringArg(),\n },\n resolve: async (parent, { email, password }, context) => {\n const user = await context.prisma.users.findOne({\n where: {\n EMAIL : email,\n },\n })\n if (!user) {\n return new Error(`No user found for email: ${email}`)\n }\n const passwordValid = await compare(password, user.PASSWORD)\n if (!passwordValid) {\n return new Error('Invalid password')\n }\n const token = await sign({ userId: user.id }, APP_SECRET)\n return {\n token ,\n user,\n }\n },\n })\n },\n})\n```\n\nMy problem is when i try to mutate the login method with token return value , it works perfectly and here is my mutation\n\n```\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n token\n}\n}\n```\n\nResponse\n\n```\n{\n \"data\": {\n \"login\": {\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjMyLCJpYXQiOjE1OTcxMDY0OTd9.d1Ra32ArCXumBfzg2vE1-xeea21cAkNwWBJPm3U3akM\"\n }\n }\n}\n```\n\nAs shown . this works perfectly . now as mentioned the AuthPayload return the token and the users type\nwhen i try to mutate with user :-\n\n```\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n token\n users{\n USERNAME\n FIRST_NAME\n }\n}\n}\n```\n\nit gives me this error\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field AuthPayload.users.\",\n \"locations\": [\n {\n \"line\": 4,\n \"column\": 5\n }\n ],\n \"path\": [\n \"login\",\n \"users\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Cannot return null for non-nullable field AuthPayload.users.\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:595:13)\",\n \" at completeValueCatchingError (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:530:19)\",\n \" at resolveField (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:461:10)\",\n \" at executeFields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:297:18)\",\n \" at collectAndExecuteSubfields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:748:10)\",\n \" at completeObjectValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:738:10)\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:626:12)\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:592:21)\",\n \" at C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:527:16\"\n ]\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\ni tried to attach the debugger to see where is the null occur\nand i didn't found any nullable values\n\nhere is a picture of vscode before return value , the token and user object are defined\nVSCode Debugger picture\n\n========================================\n\nCode:\n```text\n### This file was generated by Nexus Schema\n### Do not make changes to this file directly\n\n\ntype AuthPayload {\n  token: String!\n  users: users!\n}\n\nscalar DateTime\n\ntype Mutation {\n  login(email: String, password: String): AuthPayload!\n  signup(CREATED_BY: String, EMAIL: String, FIRST_NAME: String, IS_ACTIVE: Boolean, PASSWORD: String, USERNAME: String): AuthPayload!\n}\n\ntype Query {\n  me: users\n}\n\ntype users {\n  CREATED_BY: String!\n  CREATED_ON: DateTime\n  EMAIL: String!\n  FIRST_NAME: String!\n  id: Int!\n  IS_ACTIVE: Boolean!\n  LAST_NAME: String\n  MODIFIED_BY: String\n  MODIFIED_ON: DateTime\n  ORGANIZATION_ID: String\n  PASSWORD: String!\n  PHONE: String\n  USERNAME: String!\n}\n```\n\n```text\nconst Mutation = mutationType({\n  definition(t) {\n    t.field('signup', {\n      type: 'AuthPayload',\n      args: {\n        FIRST_NAME: stringArg({ nullable: true }),\n        EMAIL: stringArg(),\n        PASSWORD: stringArg(),\n        IS_ACTIVE: booleanArg(),\n        USERNAME: stringArg(),\n        CREATED_BY: stringArg(),\n      },\n      resolve: async (parent, { FIRST_NAME, EMAIL, PASSWORD ,IS_ACTIVE ,USERNAME,CREATED_BY }, ctx) => {\n        const hashedPassword = await hash(PASSWORD, 10)\n\n         const user = await ctx.prisma.users.create({\n          data: {\n            FIRST_NAME,\n            EMAIL,\n            PASSWORD: hashedPassword,\n            IS_ACTIVE,\n            USERNAME,\n            CREATED_BY\n          },\n        })\n        return {\n          token: sign({ userId: user.id }, APP_SECRET),\n          user,\n        }\n      },\n    })\n\n    t.field('login', {\n      type: 'AuthPayload',\n      args: {\n        email: stringArg(),\n        password: stringArg(),\n      },\n      resolve: async (parent, { email, password }, context) => {\n        const user = await context.prisma.users.findOne({\n          where: {\n            EMAIL : email,\n          },\n        })\n        if (!user) {\n          return new Error(`No user found for email: ${email}`)\n        }\n        const passwordValid = await compare(password, user.PASSWORD)\n        if (!passwordValid) {\n          return new Error('Invalid password')\n        }\n        const token = await sign({ userId: user.id }, APP_SECRET)\n        return {\n          token ,\n          user,\n        }\n      },\n    })\n  },\n})\n```\n\n```text\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n  token\n}\n}\n```\n\n```text\n{\n  \"data\": {\n    \"login\": {\n      \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjMyLCJpYXQiOjE1OTcxMDY0OTd9.d1Ra32ArCXumBfzg2vE1-xeea21cAkNwWBJPm3U3akM\"\n    }\n  }\n}\n```\n\n```text\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n  token\n    users{\n    USERNAME\n    FIRST_NAME\n  }\n}\n}\n```\n\n```text\n{\n  \"errors\": [\n    {\n      \"message\": \"Cannot return null for non-nullable field AuthPayload.users.\",\n      \"locations\": [\n        {\n          \"line\": 4,\n          \"column\": 5\n        }\n      ],\n      \"path\": [\n        \"login\",\n        \"users\"\n      ],\n      \"extensions\": {\n        \"code\": \"INTERNAL_SERVER_ERROR\",\n        \"exception\": {\n          \"stacktrace\": [\n            \"Error: Cannot return null for non-nullable field AuthPayload.users.\",\n            \"    at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:595:13)\",\n            \"    at completeValueCatchingError (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:530:19)\",\n            \"    at resolveField (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:461:10)\",\n            \"    at executeFields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:297:18)\",\n            \"    at collectAndExecuteSubfields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:748:10)\",\n            \"    at completeObjectValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:738:10)\",\n            \"    at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:626:12)\",\n            \"    at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:592:21)\",\n            \"    at C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:527:16\"\n          ]\n        }\n      }\n    }\n  ],\n  \"data\": null\n}\n```\n\n```text\nuser\n```\n\n```text\nusers\n```\n\n```text\nusers\n```\n\n```text\nnull\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":383,"estimatedTokens":2465}}74{"id":"stack-72371382","source":"stackoverflow","questionId":72371382,"title":"Which is better - Int autoincrement id or cuid for PostgreSQL prisma schema?","tags":["javascript","reactjs","postgresql","next.js","prisma"],"text":"Title: Which is better - Int autoincrement id or cuid for PostgreSQL prisma schema?\nTags: javascript, reactjs, postgresql, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nWe use Postgres and prisma for our Next.js app. Previous developers have used cuid for every table on our schema. For some reasons we are restructuring the tables and I was wondering would it be better to use int ids? Would it result in any performance gain?\n\nWhat are the tradeoffs between using Int autoincrement id vs cuid for Postgres prisma client?\n\nIf you start comparing GUID vs Int ids for Postgres, please quote authentic reference proving that cuid is mapped to guid for Postgres.\n\n========================================\n\nTop Answer:\nA sequence generating `bigint` values will certainly be faster than even the most efficient CUID or GUID algorithm, and the result will need less storage space.\n\nThe only good reasons to use something else like a CUID or GUID are\n\nyou have cryptographic requirements to obscure the creation order (but CUID doesn't do that)\n\nyou need to generate primary keys outside the database and in a distributed environment\n\n========================================\n\nCode:\n```text\nCUID\n```\n\n```text\nCUID\n```\n\n```text\ncuid2\n```\n\n```text\nautoincrement()\n```\n\n```text\ncuid2\n```\n\n```text\ncuid2\n```\n\n```text\nautoincrement()\n```\n\n```text\nbigint\n```\n\n========================================\n\nComments:\n- Maybe here You can find some answer cybertec-postgresql.com/en/&hellip;\n- What is cuid? Please add some description.\n- @LaurenzAlbe usecuid.org\n- CUID should be composed of timestamp+entropy+sequence number, is it not enough to obscure creation order? is there any attack which can exploit through CUID\n- @l2ysho You could look at the timestamp part, that would show the creation order.\n- NOTE: `cuid@2` (github.com/paralleldrive/cuid2/#improvements-over-cuid) addresses quite a few flaws.\n- What about not wanting to leak competitive intelligence? e.g. number of registered users, etc.\n- @OlivierLalonde Leak to whom? The end user doesn't see artificially generated keys. And anyone who breaks into the database (e.g., with SQL injection) can query that information anyway. Finally, you could define your sequence as `INCREMENT BY 7` to obscure the count.\n- @LaurenzAlbe to anyone who uses your app or api, through the ids shown in urls or api responses. PlanetScale has a good article on this (planetscale.com/blog/why-we-chose-nanoids-for-planetscales-&zwnj;&#8203;api). They use regular auto increment ids internally, but also have public ids using NanoIDs for any records that are exposed publicly.\n- @RomanScher Nobody forces you to expose the artificial primary key through an API.\n- @LaurenzAlbe - I just saw this post as I was looking for something to clarify this same question. But just curious to learn about a few things as I dont have much info on this topic. Would you not want to obscure your UserID or Profile ID? AutoIncrement would be too simple and dont seem like a great alternative. Can you suggest a better alternative? And how can we apply this in distributed environments? thank you\n- @Ahmed This is not about relevant externally visible identifiers like your social security number, which you can consider information you don't want to promulgate. It is about internal numbers used in a database. Is it security relevant information that your address in some database is stored with the ID 63027? Particularly since that information doesn't have to be exposed via an API. If somebody breaks into the database to steal data, this number is the least of your worries.\n- @LaurenzAlbe - In that case we pretty much dont need this at all. And simply live with auto increments. Simpler terms may help more for future references. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":73,"estimatedTokens":941}}75{"id":"stack-70686221","source":"stackoverflow","questionId":70686221,"title":"How can I query a string in a non case sensitive way?","tags":["typescript","postgresql","prisma"],"text":"Title: How can I query a string in a non case sensitive way?\nTags: typescript, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nMy question is as simple as that : I have a query and I am looking for a match on a string such as :\n\n```\nconst test_name = 'ExAmPlE'\nconst database_resources = await prisma.market.findMany({\n where: {\n name: test_name\n }\n})\n```\n\nI can use `string.toLowerCase()` but only on specific use cases\n\nHow can I get all of the rows where name can be anything such as `Example`, `ExAMple` or `example` but not any other key such as `Exàmplé` ?\n\n========================================\n\nTop Answer:\nYou can try out the following:\n\n```\nprisma.market.findMany({\n where: {\n name: {\n contains: filter\n }\n }\n})\n```\n\nAnd if you want to filter using more than one property, you can try out the following\n\n```\nprisma.market.findMany({\n where: {\n OR: [\n {\n name: {\n contains: filter\n }\n },\n {\n description: {\n contains: filter\n }\n }\n ]\n }\n})\n```\n\n========================================\n\nCode:\n```text\nconst test_name = 'ExAmPlE'\nconst database_resources = await prisma.market.findMany({\n    where: {\n        name: test_name\n    }\n})\n```\n\n```text\nstring.toLowerCase()\n```\n\n```text\nExample\n```\n\n```text\nExAMple\n```\n\n```text\nexample\n```\n\n```text\nExàmplé\n```\n\n```js\nconst test_name = 'ExAmPlE'\nconst database_resources = await prisma.market.findMany({\n    where: {\n        name: {\n            equals: test_name,\n            mode: 'insensitive'\n        }\n    }\n})\n```\n\n```text\nmode: 'insensitive'\n```\n\n```text\nmode: 'insensitive'\n```\n\n```text\nprisma.market.findMany({\n  where: {\n    name: {\n      contains: filter\n    }\n  }\n})\n```\n\n```text\nprisma.market.findMany({\n  where: {\n    OR: [\n      {\n        name: {\n          contains: filter\n        }\n      },\n      {\n        description: {\n          contains: filter\n        }\n      }\n    ]\n  }\n})\n```\n\n```text\nconst search = 'ExAmPlE';\nconst results = await prisma.market.findMany({\n    where: {\n        name: {\n            contains: search,\n            mode: 'insensitive',\n        },\n    },\n});\n```\n\n```text\nconst search = 'ExAmPlE';\nconst results = await prisma.market.findMany({\n    where: {\n        OR: [\n            {\n                name: {\n                    contains: search,\n                    mode: 'insensitive',\n                },\n            },\n            {\n                otherField: {\n                    contains: search,\n                    mode: 'insensitive',\n                },\n            },\n        ],\n    },\n});\n```\n\n========================================\n\nComments:\n- I see how it could help in some circumstances but how can it help for case sensitivity ?\n- Your second code block is inaccurate. `contains` cannot process wildcards `%`, instead use Prisma.queryRaw() or use the full-text search preview feature. github.com/prisma/prisma/discussions/3159","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":176,"estimatedTokens":712}}76{"id":"stack-61449430","source":"stackoverflow","questionId":61449430,"title":"How to use DECIMAL(10,2) in prisma migrate tool?","tags":["prisma","prisma-graphql","nexus-prisma"],"text":"Title: How to use DECIMAL(10,2) in prisma migrate tool?\nTags: prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nI need save `DECIMAL(10,2)` in database. In `MySQL` there is `DECIMAL` type.\n\nMySQL docs: \n\n https://dev.mysql.com/doc/refman/8.0/en/fixed-point-types.html\n\nPrisma 2.0 docs:\n\n https://www.prisma.io/docs/reference/database-connectors/mysql\n\nPossible Prisma 2.0 flows:\n\n https://www.prisma.io/docs/understand-prisma/introduction#typical-prisma-workflows\n\n- I am using `Prisma Migrate` flow and see that mapping is constrained.\n\n- I see that it can be done in `Introspection` flow.\n\n### Are there any plans of support mysql data types like `DECIMAL(10,2)` in `Prisma Migrate` flow?\n\n========================================\n\nTop Answer:\nCurrently `prisma migrate` doesn't support the `Decimal` type. You can track the issue for custom DB types here\n\nAs a workaround, you would have to use a custom migration tool and specify the `Decimal` field that you require and then run `prisma introspect` which will get all the fields from your DB and populate the `schema.prisma`.\n\n========================================\n\nCode:\n```text\nDECIMAL(10,2)\n```\n\n```text\nMySQL\n```\n\n```text\nDECIMAL\n```\n\n```text\nPrisma Migrate\n```\n\n```text\nIntrospection\n```\n\n```text\nDECIMAL(10,2)\n```\n\n```text\nPrisma Migrate\n```\n\n```js\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n \nmodel Product {\n  id Int @id @default(autoincrement())\n  code String\n  price Decimal @db.Decimal(9,2)\n}\n```\n\n```text\nprisma migrate\n```\n\n```text\nDecimal\n```\n\n```text\nDecimal\n```\n\n```text\nprisma introspect\n```\n\n```text\nschema.prisma\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.820Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":99,"estimatedTokens":425}}77{"id":"stack-74089665","source":"stackoverflow","questionId":74089665,"title":"next-auth credentials provider authorize type error","tags":["typescript","next.js","prisma","next-auth"],"text":"Title: next-auth credentials provider authorize type error\nTags: typescript, next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nI am only using a single `CredentialsProvider` in next-auth but I'm confused about how to handle `async authorize()` with a custom user interface.\n\nI defined the user interface in `types/next-auth.d.ts` as follows:\n\n```\nimport NextAuth from \"next-auth\"\n\ndeclare module \"next-auth\" {\n interface User {\n id: string\n address: string\n name?: string\n }\n}\n```\n\nThis is the provider definition in `[...nextauth].ts`:\n\n```\nCredentialsProvider({\n name: \"Ethereum\",\n credentials: {\n message: {\n label: \"Message\",\n type: \"text\",\n },\n signature: {\n label: \"Signature\",\n type: \"text\",\n },\n },\n async authorize(credentials) {\n try {\n const nextAuthUrl = process.env.NEXTAUTH_URL\n if (!nextAuthUrl) return null\n if (!credentials) return null\n\n // [verify the credential here]\n // \"message\" contains the verified information\n\n let user = await prisma.user.findUnique({\n where: {\n address: message.address,\n },\n })\n if (!user) {\n user = await prisma.user.create({\n data: {\n address: message.address,\n },\n })\n }\n\n return {\n id: user.id,\n address: user.address,\n name: user.name\n }\n } catch (e) {\n console.error(e)\n return null\n }\n },\n})\n```\n\nNow I see the typescript error in the `async authorize(credentials)`\n\n```\nType '(credentials: Record | undefined) => Promise' is not assignable to type '(credentials: Record | undefined, req: Pick) => Awaitable'.\n Type 'Promise' is not assignable to type 'Awaitable'.\n Type 'Promise' is not assignable to type 'PromiseLike'.\n Types of property 'then' are incompatible.\n Type '(onfulfilled?: ((value: { id: string; address: string; name: string | null; } | null) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | ... 1 more ... | unde...' is not assignable to type '(onfulfilled?: ((value: User | null) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike'.\n Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.\n Types of parameters 'value' and 'value' are incompatible.\n Type '{ id: string; address: string; name: string | null; } | null' is not assignable to type 'User | null'.\n Type '{ id: string; address: string; name: string | null; }' is not assignable to type 'User'.\n Types of property 'name' are incompatible.\n Type 'string | null' is not assignable to type 'string | undefined'.\n Type 'null' is not assignable to type 'string | undefined'.\n```\n\n### Docs\n\nCredentials provider\n\nNextAuth with typescript/extend interface\n\n========================================\n\nTop Answer:\nGot the same issue. Since I didn't want to turn of strict mode in .tsconfig, I simply went with parsing the returned object of `authorize()` to any...\n\n```\nasync authorize(credentials) {\n // ...\n return {\n // ...\n } as any. // I don't like it, but I think it's better than turning off strict mode.\n\nAlso it doesn't destroy type-safety in the up since the next step using the returned type would be in the `jwt({user})` callback, and the typing still works there just fine.\n\n========================================\n\nCode:\n```js\nimport NextAuth from \"next-auth\"\n\ndeclare module \"next-auth\" {\n  interface User {\n    id: string\n    address: string\n    name?: string\n  }\n}\n```\n\n```js\nCredentialsProvider({\n  name: \"Ethereum\",\n  credentials: {\n    message: {\n      label: \"Message\",\n      type: \"text\",\n    },\n    signature: {\n      label: \"Signature\",\n      type: \"text\",\n    },\n  },\n  async authorize(credentials) {\n    try {\n      const nextAuthUrl = process.env.NEXTAUTH_URL\n      if (!nextAuthUrl) return null\n      if (!credentials) return null\n\n      // [verify the credential here]\n      // \"message\" contains the verified information\n\n      let user = await prisma.user.findUnique({\n        where: {\n          address: message.address,\n        },\n      })\n      if (!user) {\n        user = await prisma.user.create({\n          data: {\n            address: message.address,\n          },\n        })\n      }\n\n      return {\n        id: user.id,\n        address: user.address,\n        name: user.name\n      }\n    } catch (e) {\n      console.error(e)\n      return null\n    }\n  },\n})\n```\n\n```text\nType '(credentials: Record<\"message\" | \"signature\", string> | undefined) => Promise<{ id: string; address: string; name: string | null; } | null>' is not assignable to type '(credentials: Record<\"message\" | \"signature\", string> | undefined, req: Pick<RequestInternal, \"body\" | \"query\" | \"headers\" | \"method\">) => Awaitable<...>'.\n  Type 'Promise<{ id: string; address: string; name: string | null; } | null>' is not assignable to type 'Awaitable<User | null>'.\n    Type 'Promise<{ id: string; address: string; name: string | null; } | null>' is not assignable to type 'PromiseLike<User | null>'.\n      Types of property 'then' are incompatible.\n        Type '<TResult1 = { id: string; address: string; name: string | null; } | null, TResult2 = never>(onfulfilled?: ((value: { id: string; address: string; name: string | null; } | null) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | unde...' is not assignable to type '<TResult1 = User | null, TResult2 = never>(onfulfilled?: ((value: User | null) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => PromiseLike<...>'.\n          Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.\n            Types of parameters 'value' and 'value' are incompatible.\n              Type '{ id: string; address: string; name: string | null; } | null' is not assignable to type 'User | null'.\n                Type '{ id: string; address: string; name: string | null; }' is not assignable to type 'User'.\n                  Types of property 'name' are incompatible.\n                    Type 'string | null' is not assignable to type 'string | undefined'.\n                      Type 'null' is not assignable to type 'string | undefined'.\n```\n\n```text\nCredentialsProvider\n```\n\n```text\nasync authorize()\n```\n\n```text\ntypes/next-auth.d.ts\n```\n\n```text\n[...nextauth].ts\n```\n\n```text\nasync authorize(credentials)\n```\n\n```text\n\"strict\": false\n```\n\n```text\n\"strict\": false\n```\n\n```js\nasync authorize(credentials) {\n  // ...\n  return {\n    // ...\n  } as any. // <-- This here\n}\n```\n\n```text\nauthorize()\n```\n\n```text\njwt({user})\n```\n\n```text\nasync authorize(credentials, req): Promise<any> {\n   //code here\n}\n```\n\n```text\nimport nextAuth from \"next-auth/next\";\nimport { AuthOptions } from \"next-auth\";\nimport CredentialsProvider from \"next-auth/providers/credentials\";\n\nexport const authOptions: AuthOptions = {\n  providers: [\n    CredentialsProvider({\n      credentials: {\n        email: {},\n        password: {},\n      },\n      async authorize(credentials) {\n        const user = { id: \"hello\", name: \"jay\", password: \"dave\" };\n        if (!user || !user.password) return null;\n\n        const passwordsMatch = user.password === credentials?.password;\n\n        if (passwordsMatch) return user;\n        return null;\n      },\n    }),\n  ],\n};\n\nexport default nextAuth(authOptions);\n```\n\n```text\nexport interface CredentialsConfig<\n  C extends Record<string, CredentialInput> = Record<string, CredentialInput>\n> extends CommonProviderOptions {\n  type: \"credentials\"\n  credentials: C\n  authorize: (\n    credentials: Record<keyof C, string> | undefined,\n    req: Pick<RequestInternal, \"body\" | \"query\" | \"headers\" | \"method\">\n  ) => Awaitable<User | null>\n}\n```\n\n```text\nexport interface DefaultUser {\n  id: string\n  name?: string | null\n  email?: string | null\n  image?: string | null\n}\n\n/**\n * The shape of the returned object in the OAuth providers' `profile` callback,\n * available in the `jwt` and `session` callbacks,\n * or the second parameter of the `session` callback, when using a database.\n *\n * [`signIn` callback](https://next-auth.js.org/configuration/callbacks#sign-in-callback) |\n * [`session` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) |\n * [`jwt` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) |\n * [`profile` OAuth provider callback](https://next-auth.js.org/configuration/providers#using-a-custom-provider)\n */\nexport interface User extends DefaultUser {}\n```\n\n```text\nCredentials({\n      authorize: async (credentials) => {\n        // console.log({ credentials });\n        // Validated the fields if correct or not\n        const validateFields = LoginSchema.safeParse(credentials);\n        if (validateFields.success) {\n          // If Success check if user valid\n          const user = await fetch(\"http://localhost:3000/auth\",{\n            method:\"POST\",\n            body:JSON.stringify({\n              email:validateFields.data.email,\n              password:validateFields.data.password\n            }),\n            headers:{\n              \"Content-type\":\"application/json\"\n            }\n          })\n          // const user = { name: \"jay\", password: \"dave\" };\n          // If user valid return user object\n          if(user) return user.json()\n        }\n        // If not just return null\n        return null;\n      },\n```\n\n========================================\n\nComments:\n- any update on this? 2025?","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":332,"estimatedTokens":2351}}78{"id":"stack-70599976","source":"stackoverflow","questionId":70599976,"title":"Prisma query engine not found on mac M1","tags":["node.js","apple-m1","prisma","darwin","query-engine"],"text":"Title: Prisma query engine not found on mac M1\nTags: node.js, apple-m1, prisma, darwin, query-engine\nSource: Stack Overflow\n\nQuestion:\nI'm having an issue with running Prisma in my project. Running `npx prisma generate` works, but then running my app I get:\n\n```\n/Users/user/Desktop/project/node_modules/@prisma/client/runtime/index.js:36466\n4:29:05 PM web.1 | throw new PrismaClientInitializationError(errorText, this.config.clientVersion);\n4:29:05 PM web.1 | ^\n4:29:05 PM web.1 | PrismaClientInitializationError: Query engine library for current platform \"darwin\" could not be found.\n4:29:05 PM web.1 | You incorrectly pinned it to darwin\n4:29:05 PM web.1 | This probably happens, because you built Prisma Client on a different platform.\n4:29:05 PM web.1 | (Prisma Client looked in \"/Users/user/Desktop/project/node_modules/@prisma/client/runtime/libquery_engine-darwin.dylib.node\")\n```\n\nI've noticed that the `libquery_engine-darwin.dylib.node` file actually exists as `libquery_engine-darwin-arm64.dylib.node`. My `schema.prisma` file includes:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n bindaryTargets = [\"native\", \"darwin\"]\n}\n```\n\nI can't seem to figure out how to generate the right query engine binary with `darwin` and not `darwin-arm64`, or have the clientVersion look for the latter.\n\nHere's `npx prisma -v`:\n\n```\nprisma : 3.7.0\n@prisma/client : 3.7.0\nCurrent platform : darwin-arm64\nQuery Engine (Node-API) : libquery-engine 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)\nMigration Engine : migration-engine-cli 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/migration-engine-darwin-arm64)\nIntrospection Engine : introspection-core 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)\nFormat Binary : prisma-fmt 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)\nDefault Engines Hash : 8746e055198f517658c08a0c426c7eec87f5a85f\nStudio : 0.445.0\n```\n\nI'm running on a new M1 iMac. Any help would be so so appreciated, thanks!\n\n========================================\n\nTop Answer:\nFor me mac M2, its work with `darwin-arm64`\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n binaryTargets = [\"native\", \"darwin-arm64\"]\n}\n```\n\n========================================\n\nCode:\n```text\n/Users/user/Desktop/project/node_modules/@prisma/client/runtime/index.js:36466\n4:29:05 PM web.1 |        throw new PrismaClientInitializationError(errorText, this.config.clientVersion);\n4:29:05 PM web.1 |              ^\n4:29:05 PM web.1 |  PrismaClientInitializationError: Query engine library for current platform \"darwin\" could not be found.\n4:29:05 PM web.1 |  You incorrectly pinned it to darwin\n4:29:05 PM web.1 |  This probably happens, because you built Prisma Client on a different platform.\n4:29:05 PM web.1 |  (Prisma Client looked in \"/Users/user/Desktop/project/node_modules/@prisma/client/runtime/libquery_engine-darwin.dylib.node\")\n```\n\n```text\ngenerator client {\n  provider       = \"prisma-client-js\"\n  bindaryTargets = [\"native\", \"darwin\"]\n}\n```\n\n```text\nprisma                  : 3.7.0\n@prisma/client          : 3.7.0\nCurrent platform        : darwin-arm64\nQuery Engine (Node-API) : libquery-engine 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)\nMigration Engine        : migration-engine-cli 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/migration-engine-darwin-arm64)\nIntrospection Engine    : introspection-core 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)\nFormat Binary           : prisma-fmt 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)\nDefault Engines Hash    : 8746e055198f517658c08a0c426c7eec87f5a85f\nStudio                  : 0.445.0\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nlibquery_engine-darwin.dylib.node\n```\n\n```text\nlibquery_engine-darwin-arm64.dylib.node\n```\n\n```text\nschema.prisma\n```\n\n```text\ndarwin\n```\n\n```text\ndarwin-arm64\n```\n\n```text\nnpx prisma -v\n```\n\n```text\nbindaryTargets\n```\n\n```text\nbinaryTargets\n```\n\n```text\ngenerator client {\n  provider      = \"prisma-client-js\"\n  binaryTargets = [\"native\", \"darwin-arm64\"]\n}\n```\n\n```text\ndarwin-arm64\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n```\n\n```text\ngenerator client {\n    provider      = \"prisma-client-js\"\n    binaryTargets = [\"native\", \"darwin\", \"darwin-arm64\"]\n}\n```\n\n```text\nnpx prisma generate\n```\n\n========================================\n\nComments:\n- For anyone coming across this in the future, check your node version against the allowed versions for Prisma... (<=v20.x). I ran `brew install`, which auto updates everything including setting my node version to 21.x and that caused this issue for me.","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":156,"estimatedTokens":1238}}79{"id":"stack-69023136","source":"stackoverflow","questionId":69023136,"title":"Auto-incrementing from custom value in prisma + postgresql","tags":["postgresql","prisma"],"text":"Title: Auto-incrementing from custom value in prisma + postgresql\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using a prismia db client with postgresql and I'd like to start auto incrementing an integer field from 0 instead of 1. In other words, how can I write a model so that it starts from 0?\n\nHere's the modal I have.\n\n```\nmodel SortableItem {\n id String @id @default(uuid())\n name String\n order Int @default(autoincrement())\n}\n```\n\nWith this implementation, when a record is inserted for the first time, the `order` starts from 1, but I'd like it to start from 0.\n\nI know postgresql has `RESTART` to achieve this, but I couldn't find anything equivalent for prisma ORM syntax.\n\n```\nALTER SEQUENCE tablename_columnname_seq RESTART WITH 0;\n```\n\n========================================\n\nCode:\n```text\nmodel SortableItem {\n  id    String @id @default(uuid())\n  name  String\n  order Int @default(autoincrement())\n}\n```\n\n```sql\nALTER SEQUENCE tablename_columnname_seq RESTART WITH 0;\n```\n\n```text\norder\n```\n\n```text\nRESTART\n```\n\n```text\nprisma migrate dev --create-only\n```\n\n```text\n.sql\n```\n\n```text\nprisma migrate dev\n```\n\n========================================\n\nComments:\n- It should be `ALTER SEQUENCE \"tablename_columnname_seq\" RESTART WITH 0;`\n- I see. I was not aware of the `--create-only` flag. Thanks.\n- This is the most beautiful day of my life 😍","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":66,"estimatedTokens":345}}80{"id":"stack-74876237","source":"stackoverflow","questionId":74876237,"title":"Can't migrate schema using Prisma with Supabase","tags":["postgresql","prisma","supabase","supabase-database"],"text":"Title: Can't migrate schema using Prisma with Supabase\nTags: postgresql, prisma, supabase, supabase-database\nSource: Stack Overflow\n\nQuestion:\nWhen I use the Postgres database on `Supabase` I run the following command, `npx prisma migrate dev --name init`, but I get the following error (first command in screenshot):\n\n```\nError: db error: FATAL: bouncer config error\n 0: migration_core::state::DevDiagnostic\n at migration-engine/core/src/state.rs:251\n```\n\nWhen I use `railway.app`, with a Postgres database it migrates successfully (second command in screenshot).\n\nhttps://i.sstatic.net/FGXJx.png\n\n========================================\n\nCode:\n```text\nError: db error: FATAL: bouncer config error\n   0: migration_core::state::DevDiagnostic\n             at migration-engine/core/src/state.rs:251\n```\n\n```text\nSupabase\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n```text\nrailway.app\n```\n\n========================================\n\nComments:\n- Alternatively: You can use \"directUrl\" in the \"datasource db\"-settings of the schema and set the Url there.","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":42,"estimatedTokens":265}}81{"id":"stack-62046070","source":"stackoverflow","questionId":62046070,"title":"prisma2: how to fetch nested fields?","tags":["javascript","node.js","graphql","prisma","prisma-graphql"],"text":"Title: prisma2: how to fetch nested fields?\nTags: javascript, node.js, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nIn prisma 1 I have used fragment to fetch the nested fields.\n\nFor example:\n\n```\nconst mutations = {\n async createPost(_, args, ctx) {\n const user = await loginChecker(ctx);\n const post = await prisma.post\n .create({\n data: {\n author: {\n connect: {\n id: user.id,\n },\n },\n title: args.title,\n body: args.body,\n published: args.published,\n },\n })\n .$fragment(fragment);\n\n return post;\n },\n};\n```\n\nbut seems like in prisma2 it is not supported. because by running this on playground,\n\n```\nmutation CREATEPOST {\n createPost(\n title: \"How to sleep?\"\n body: \"Eat, sleep, repaet\"\n published: true\n ) {\n title\n body\n published\n author {\n id\n }\n }\n}\n```\n\nI am getting,\n\n```\n\"prisma.post.create(...).$fragment is not a function\",\n```\n\n========================================\n\nCode:\n```text\nconst mutations = {\n  async createPost(_, args, ctx) {\n    const user = await loginChecker(ctx);\n    const post = await prisma.post\n      .create({\n        data: {\n          author: {\n            connect: {\n              id: user.id,\n            },\n          },\n          title: args.title,\n          body: args.body,\n          published: args.published,\n        },\n      })\n      .$fragment(fragment);\n\n    return post;\n  },\n};\n```\n\n```text\nmutation CREATEPOST {\n  createPost(\n    title: \"How to sleep?\"\n    body: \"Eat, sleep, repaet\"\n    published: true\n  ) {\n    title\n    body\n    published\n    author {\n      id\n    }\n  }\n}\n```\n\n```text\n\"prisma.post.create(...).$fragment is not a function\",\n```\n\n```text\nconst result = await prisma.user.findOne({\n  where: { id: 1 },\n  include: { posts: true },\n})\n```\n\n```text\nconst result = await prisma.user.findOne({\n  where: { id: 1 },\n  include: {\n    posts: {\n      include: {\n        author: true,\n      }\n    },\n  },\n})\n```\n\n========================================\n\nComments:\n- suppose I include {post and author} in createComment resolver. when running this from playground: `mutation CREATECOMMENT { createComment(text: \"yep, very bad post dude\", postId: 4) { id text post { id title author: {id} } author { name } } }` here how can I get posts {author:id} ?\n- So that has more to do with how your schema is defined than prisma itself. Assuming createComment returns a `Comment`, the `Comment` type needs to have `post` as a queryable field. And the `Post` type needs to have `author` as a queryable field.\n- you can see from my data model: gist.github.com/ashiqdev/17d96ac1db30c35ef8e7622992cab035 comment has relation with post and post has relation with author. but, when created a comment I included { author: true, post: true,}. so, I got post and authors direct queries. but when I try to get post {author {id}} I can't get it. In prisma1 by using fragment I used to got it.\n- The prisma client supports nesting includes as well `.findOne({ include: { post: { include: { author: true } } } })`\n- with nested includes, can i also add where parts so to only get those total records including all the hierarchy where a specific element deep in the tree has a specific value?","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":134,"estimatedTokens":787}}82{"id":"stack-54313128","source":"stackoverflow","questionId":54313128,"title":"Querying NOT NULL GraphQL with Prisma","tags":["graphql","apollo","prisma"],"text":"Title: Querying NOT NULL GraphQL with Prisma\nTags: graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nSchema:\n\n```\ntype TrackUser {\n id: ID! @unique\n createdAt: DateTime!\n user: User #note there is no `!`\n}\ntype User {\n id: ID! @unique\n name: String! @unique\n}\n```\n\nI want to get Alls `TrackUser` where `User` is not null. What would be the query?\n\n========================================\n\nTop Answer:\nthis works, but I guess it is just a hack..\n\n```\nquery TrackUsersQuery($orderBy: TrackUserOrderByInput!, $where: TrackUserWhereInput, $first: Int, $skip: Int) {\n trackUsers(where: $where, orderBy: $orderBy, first: $first, skip: $skip) {\n id\n createdAt\n user {\n id\n name\n }\n }\n}\n\nvariables = {\n where: {\n user: {\n name_contains: ''\n }\n }\n}\n```\n\nUPDATE:\n\nFor Prisma2, here you have the possibilities:\n\nFor products that have no invoice, you can use the following:\n\n```\nconst data = await prisma.product.findMany({\n where: {\n invoices: {\n none: {\n id: undefined,\n },\n },\n },\n})\n```\n\nAnd for Invoices that do not have a product associated:\n\n```\nconst data = await prisma.invoice.findMany({\n where: {\n productId: null,\n },\n})\n```\n\nmore details here: https://github.com/prisma/prisma/discussions/3461\n\n========================================\n\nCode:\n```text\ntype TrackUser {\n  id: ID! @unique\n  createdAt: DateTime!\n  user: User #note there is no `!`\n}\ntype User {\n  id: ID! @unique\n  name: String! @unique\n}\n```\n\n```text\nTrackUser\n```\n\n```text\nUser\n```\n\n```text\nquery c {\n  trackUsers(where: { NOT: [{ user: null }] }) {\n    name\n  }\n}\n```\n\n```text\nquery TrackUsersQuery($orderBy: TrackUserOrderByInput!, $where: TrackUserWhereInput, $first: Int, $skip: Int) {\n  trackUsers(where: $where, orderBy: $orderBy, first: $first, skip: $skip) {\n    id\n    createdAt\n    user {\n      id\n      name\n    }\n  }\n}\n\n\nvariables = {\n  where: {\n    user: {\n      name_contains: ''\n    }\n  }\n}\n```\n\n```text\nconst data = await prisma.product.findMany({\n    where: {\n      invoices: {\n        none: {\n          id: undefined,\n        },\n      },\n    },\n})\n```\n\n```text\nconst data = await prisma.invoice.findMany({\n    where: {\n      productId: null,\n    },\n})\n```\n\n========================================\n\nComments:\n- You have no way to filter (at least you haven't shown us any) so it's not possible.\n- Is this question specific to `prisma`?\n- Right it is with prisma.\n- Thanks for editing the question Alan :)\n- It is with prisma. Prisma is generated a chema for you.\n- And how were we supposed to know that before you gave us that information?","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":159,"estimatedTokens":634}}83{"id":"stack-68658698","source":"stackoverflow","questionId":68658698,"title":"Prisma following/follower relationship schema","tags":["javascript","node.js","postgresql","database-design","prisma"],"text":"Title: Prisma following/follower relationship schema\nTags: javascript, node.js, postgresql, database-design, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a user model, and i want to add following/followers system, and for that i think i need to create a separate table that looks like this\n\n```\nid | user_id | follower_id\n1 | 20 | 45\n2 | 20 | 53\n3 | 32 | 20\n```\n\nbut i have no idea how to create the schema for that, what I've done is this:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n username String\n Follows Follows[]\n}\n\nmodel Follows {\n id Int @id @default(autoincrement())\n following_id Int?\n follower_id Int?\n user_Following User @relation(fields: [following_id], references: [id])\n user_Follower User @relation(fields: [follower_id], references: [id])\n}\n```\n\nbut that of course doesn't work and is giving me an error\n\n========================================\n\nTop Answer:\nIn Mongodb use this for self-realtion:\n\n```\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n name String?\n followedBy User[] @relation(\"UserFollows\", fields: [followedByIDs], references: [id])\n followedByIDs String[] @db.ObjectId\n following User[] @relation(\"UserFollows\", fields: [followingIDs], references: [id])\n followingIDs String[] @db.ObjectId\n}\n```\n\n========================================\n\nCode:\n```text\nid | user_id | follower_id\n1  | 20      | 45\n2  | 20      | 53\n3  | 32      | 20\n```\n\n```text\nmodel User {\n  id         Int         @id @default(autoincrement())\n  username   String\n  Follows    Follows[]\n}\n\nmodel Follows {\n  id           Int      @id @default(autoincrement())\n  following_id Int?\n  follower_id  Int?\n  user_Following    User     @relation(fields: [following_id], references: [id])\n  user_Follower     User     @relation(fields: [follower_id], references: [id])\n}\n```\n\n```text\nmodel User {\n  id        String  @id @default(autoincrement())\n  username  String\n  followers Follows[] @relation(\"following\")\n  following Follows[] @relation(\"follower\")\n}\n\nmodel Follows {\n  follower    User @relation(\"follower\", fields: [followerId], references: [id])\n  followerId  String\n  following   User @relation(\"following\", fields: [followingId], references: [id])\n  followingId String\n\n  @@id([followerId, followingId])\n}\n```\n\n```text\nfollowerId\n```\n\n```text\nfollowingId\n```\n\n```text\nFollows\n```\n\n```text\n@@id([followerId, followingId])\n```\n\n```text\nFollows\n```\n\n```text\nid\n```\n\n```json\nmodel User {\n  id            String   @id @default(auto()) @map(\"_id\") @db.ObjectId\n  name          String?\n  followedBy    User[]   @relation(\"UserFollows\", fields: [followedByIDs], references: [id])\n  followedByIDs String[] @db.ObjectId\n  following     User[]   @relation(\"UserFollows\", fields: [followingIDs], references: [id])\n  followingIDs  String[] @db.ObjectId\n}\n```\n\n========================================\n\nComments:\n- What is the error?\n- I think you made a small mistake, the relation annotation should be switched in the User Model. followers = \"following\" and following = \"follower\". Look here prisma.io/docs/concepts/components/prisma-schema/relations/&hellip;\n- That would make more sense. Thanks for pointing it out","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":135,"estimatedTokens":789}}84{"id":"stack-69886884","source":"stackoverflow","questionId":69886884,"title":"Unique constraint failed on the constraint: `User_Account_userId_key` in prisma","tags":["javascript","mysql","prisma"],"text":"Title: Unique constraint failed on the constraint: `User_Account_userId_key` in prisma\nTags: javascript, mysql, prisma\nSource: Stack Overflow\n\nQuestion:\nHi I have three models\n\n```\nmodel User {\n user_id Int @id @default(autoincrement())\n email String @unique\n name String?\n User_Account User_Account[]\n}\n\nmodel Account {\n account_id Int @id @default (autoincrement()) @unique\n email String \n bank String\n createdAt DateTime @default(now())\n User_Account User_Account[]\n\n}\nmodel User_Account {\n id Int @id @default(autoincrement())\n accountId Int \n userId Int \n User User @relation(fields: [userId], references: [user_id])\n Account Account @relation(fields: [accountId], references: [account_id])\n}\n```\n\nI am trying to seed my db like this\n\n```\nconst data = [\n {\n id: 1,\n email: 'pranit1@mf.com',\n name: 'Pranit1',\n bank: 'VCB',\n ids: [1,1]\n },\n {\n id: 2,\n email: 'pranit1@mf.com',\n name: 'Pranit1',\n bank: 'ACB',\n ids: [1,2]\n },\n {\n id: 3,\n email: 'pranit3@mf.com',\n name: 'Pranit3',\n bank: 'VCB',\n ids: [2,3]\n }\n ]\n const users = await prisma.$transaction(\n data.map(user =>\n prisma.user.upsert({\n where: { email: user.email },\n update: {},\n create: { name: user.name,\n email:user.email },\n })\n )\n );\n \n const accounts = await prisma.$transaction(\n data.map(account => \n prisma.account.upsert({\n where: { account_id: account.id },\n update: {},\n create: { bank: account.bank ,\n email :account.email },\n })\n )\n );\n\n const user_accounts = await prisma.$transaction(\n data.map(uacc =>{\n console.log(uacc);\n return prisma.user_Account.upsert({\n where: { id: uacc.id },\n update: {id: uacc.id},\n create:{\n userId: uacc.ids[0],\n accountId: uacc.ids[1] },\n })}\n )\n );\n```\n\nHowever I am getting an\n\nUnique constraint failed on the constraint: `User_Account_userId_key`\n\nThe data in prisma studio is generated as shown in the image https://i.sstatic.net/5HpZM.png\n\nI am simply trying to create users and accounts and a user can be associated with multiple accounts. Their relation is shown in the User_Account table. I cant see why I am getting a unique constraint error when I dont have the @unique tag on userId\n\n========================================\n\nTop Answer:\nI had a similar issue because `map` does not wait for **promises** to **resolve**. Instead I had to replace it with a normal `for` loop.\n\nSo if there was already a value it wont attempt to create a new value again (instead update it using upsert)\n\n========================================\n\nCode:\n```text\nmodel User {\n  user_id      Int      @id @default(autoincrement())\n  email   String   @unique\n  name    String?\n  User_Account User_Account[]\n}\n\nmodel Account {\n  account_id Int @id @default (autoincrement()) @unique\n  email String \n  bank String\n  createdAt DateTime @default(now())\n  User_Account User_Account[]\n\n}\nmodel User_Account {\n  id Int @id @default(autoincrement())\n  accountId Int \n  userId Int \n  User User @relation(fields: [userId], references: [user_id])\n  Account Account @relation(fields: [accountId], references: [account_id])\n}\n```\n\n```text\nconst data = [\n    {\n      id: 1,\n      email: 'pranit1@mf.com',\n      name: 'Pranit1',\n      bank: 'VCB',\n      ids: [1,1]\n    },\n    {\n      id: 2,\n      email: 'pranit1@mf.com',\n      name: 'Pranit1',\n      bank: 'ACB',\n      ids: [1,2]\n    },\n    {\n      id: 3,\n      email: 'pranit3@mf.com',\n      name: 'Pranit3',\n      bank: 'VCB',\n      ids: [2,3]\n    }\n  ]\n  const users = await prisma.$transaction(\n    data.map(user =>\n      prisma.user.upsert({\n        where: { email: user.email },\n        update: {},\n        create: { name: user.name,\n        email:user.email },\n      })\n    )\n  );\n  \n  const accounts = await prisma.$transaction(\n    data.map(account => \n      prisma.account.upsert({\n        where: { account_id: account.id },\n        update: {},\n        create: { bank: account.bank ,\n          email :account.email },\n      })\n    )\n  );\n\n  const user_accounts = await prisma.$transaction(\n    data.map(uacc =>{\n      console.log(uacc);\n      return prisma.user_Account.upsert({\n        where: { id: uacc.id },\n        update: {id: uacc.id},\n        create:{\n          userId: uacc.ids[0],\n        accountId: uacc.ids[1] },\n      })}\n    )\n  );\n```\n\n```text\nUser_Account_userId_key\n```\n\n```text\nmodel User {\n  id       Int       @id @default(autoincrement())\n  email    String    @unique\n  name     String?\n  accounts Account[]\n}\n\nmodel Account {\n  id        Int      @id @unique @default(autoincrement())\n  email     String\n  bank      String\n  users     User[]\n  createdAt DateTime @default(now())\n}\n```\n\n```js\nconst { PrismaClient } = require(\"@prisma/client\");\nconst prisma = new PrismaClient();\n\nasync function main() {\n    const usersData = [\n        {\n            email: \"pranit1@mf.com\",\n            name: \"Pranit1\",\n            banks: [\"VCB\", \"ACB\"],\n        },\n        {\n            email: \"pranit3@mf.com\",\n            name: \"Pranit3\",\n            banks: [\"VCB\"],\n        },\n    ];\n\n    const users = await prisma.$transaction(\n        usersData.map((user) =>\n            prisma.user.upsert({\n                where: { email: user.email },\n                update: {},\n                create: {\n                    name: user.name,\n                    email: user.email,\n                    accounts: {\n                        create: user.banks.map((bank) => ({\n                            email: user.email,\n                            bank,\n                        })),\n                    },\n                },\n            })\n        )\n    );\n}\n\nmain()\n    .catch((e) => {\n        console.error(e);\n        process.exit(1);\n    })\n    .finally(async () => {\n        await prisma.$disconnect();\n    });\n```\n\n```text\nmap\n```\n\n```text\nfor\n```\n\n```text\nawait prisma.$queryRaw`ALTER SEQUENCE \"Member_id_seq\" RESTART WITH 100;\n```\n\n```text\n@unique\n```\n\n```text\nid\n```\n\n```text\nALTER SEQUENCE tablename_id_seq RESTART;\n```\n\n```text\nUPDATE tablename SET id = DEFAULT;\n```\n\n========================================\n\nComments:\n- What kind of database are you using? Tried to reproduce but it works fine for me using Postgres\n- Thank you for your solution. I was using Mysql, though I dont see how a different database would give different results for a seemingly basic model.\n- You're welcome! I agree with you, was just keeping my mind open to possible bugs in a specific use case\n- I got this error I want to migrate data from other source to seed into new database and i dump data into json and provide it to prisma seeding. But now if i am adding new record getting this error. How can i handle this case.","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":301,"estimatedTokens":1639}}85{"id":"stack-72339652","source":"stackoverflow","questionId":72339652,"title":"Prisma client select all rows from a table","tags":["javascript","mysql","express","orm","prisma"],"text":"Title: Prisma client select all rows from a table\nTags: javascript, mysql, express, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nhow can I select everything from a table with prisma? (SELECT * FROM application)\n\n```\nconst applications = prisma.application.findMany({\n // Returns all user fields\n include: {\n posts: {\n select: {\n age: true,\n about_section: true,\n user_id: true\n },\n },\n },\n })\n console.log(applications.age)\n```\n\nHere is how my schema looks:\n\n```\nmodel application {\n application_id Int @id @default(autoincrement())\n age String? @db.VarChar(255)\n about_section String? @db.VarChar(255)\n user_id Int?\n users users? @relation(fields: [user_id], references: [user_id], onDelete: Restrict, onUpdate: Restrict, map: \"application_ibfk_1\")\n\n @@index([user_id], map: \"user_id\")\n}\n```\n\n========================================\n\nCode:\n```text\nconst applications = prisma.application.findMany({\n        // Returns all user fields\n        include: {\n            posts: {\n                select: {\n                    age: true,\n                    about_section: true,\n                    user_id: true\n                },\n            },\n        },\n    })\n    console.log(applications.age)\n```\n\n```text\nmodel application {\n  application_id Int     @id @default(autoincrement())\n  age            String? @db.VarChar(255)\n  about_section  String? @db.VarChar(255)\n  user_id        Int?\n  users          users?  @relation(fields: [user_id], references: [user_id], onDelete: Restrict, onUpdate: Restrict, map: \"application_ibfk_1\")\n\n  @@index([user_id], map: \"user_id\")\n}\n```\n\n```js\nconst users = await prisma.user.findMany()\n```\n\n```text\nconst applications = await prisma.application.findMany();\n```\n\n```text\nconst applications = await prisma.application.findMany({\n  include: {\n    users: true // will include all fields\n  }\n});\n```\n\n```text\nfindMany()\n```\n\n```text\nwhere\n```\n\n```text\ninclude\n```\n\n```text\nselect\n```\n\n```text\nSELECT * FROM application\n```\n\n```text\nusers\n```\n\n```text\nusers\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":111,"estimatedTokens":499}}86{"id":"stack-74045257","source":"stackoverflow","questionId":74045257,"title":"How to define models with nested objects in prisma?","tags":["prisma"],"text":"Title: How to define models with nested objects in prisma?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to migrate from mongoose to Prisma. Here is the model I have defined in mongoose which contains nested objects.\n\n```\nconst sourceSchema = new Schema(\n {\n data: {\n national: {\n oldState: {\n type: Array\n },\n currentState: {\n type: Array\n }\n },\n sports: {\n oldState: {\n type: Array\n },\n currentState: {\n type: Array\n }\n }\n\n }\n \n }\n);\n```\n\nPlease guide me on how can I write the model in Prisma for the mongoose schema with nested objects.\n\n========================================\n\nCode:\n```text\nconst sourceSchema = new Schema(\n    {\n        data: {\n            national: {\n                oldState: {\n                    type: Array\n                },\n                currentState: {\n                    type: Array\n                }\n            },\n            sports: {\n                oldState: {\n                    type: Array\n                },\n                currentState: {\n                    type: Array\n                }\n            }\n\n        }\n        \n    }\n);\n```\n\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"mongodb\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Source {\n  id       String    @id @default(auto()) @map(\"_id\") @db.ObjectId\n  national stateType\n  sports   stateType\n}\n\ntype stateType {\n  oldState     oldState\n  currentState currentState\n}\n\ntype oldState {\n  type String[]\n}\n\ntype currentState {\n  type String[]\n}\n```\n\n========================================\n\nComments:\n- Thanks for helping. I would like to add one tip for those stuck while defining their Prisma model. First, connect your database with Prisma. Then create dummy data in your database. Now call `npx prisma db pull` this will automatically define the model according to the data structure in the database. Doing the following steps will either give you your desired model or it will give some direction on what to search for in the documentation. This is how I got my answer. The above concept is `Prisma Introspection`","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":103,"estimatedTokens":547}}87{"id":"stack-76854414","source":"stackoverflow","questionId":76854414,"title":"prisma error: Cannot select both '$scalars: true' and a specific scalar field 'accountCompanies'","tags":["node.js","prisma"],"text":"Title: prisma error: Cannot select both '$scalars: true' and a specific scalar field 'accountCompanies'\nTags: node.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI cannot solve this error. Any help?\n\nCannot select both '$scalars: true' and a specific scalar field 'accountCompanies'.\n\n```\nmodel Account {\n id String @id @default(cuid())\n avatar String?\n lastName String\n firstName String\n\n accountCompanies AccountCompany[]\n}\n\nmodel Company {\n id String @id @default(cuid())\n name String\n\n accountCompanies AccountCompany[]\n}\n\nmodel AccountCompany {\n account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)\n accountId String\n company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)\n companyId String\n role Role @default(GENERAL)\n\n @@id(fields: [accountId, companyId])\n}\n```\n\nThe above error occurs in the code below.\n\n```\nconst account = await prisma.account.findUnique({\n where: { auth0UserId: auth0User.sub },\n include: { accountCompanies: true },\n });\n```\n\n========================================\n\nTop Answer:\nFor anyone else searching this same error message, as this was basically the only page I found for it.\n\nI had this issue due to a capitalization bug. I meant to be referencing a relationship using 'Products' with a capital 'P', but I had accidentally written 'products' with a lower case 'p' in both the 'create' and 'include' section of the Prisma query.\n\n========================================\n\nCode:\n```text\nmodel Account {\n  id String  @id @default(cuid())\n  avatar String?\n  lastName String\n  firstName String\n\n  accountCompanies AccountCompany[]\n}\n\nmodel Company {\n  id String  @id @default(cuid())\n  name String\n\n  accountCompanies AccountCompany[]\n}\n\nmodel AccountCompany {\n  account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)\n  accountId String\n  company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)\n  companyId String\n  role Role  @default(GENERAL)\n\n  @@id(fields: [accountId, companyId])\n}\n```\n\n```text\nconst account = await prisma.account.findUnique({\n    where: { auth0UserId: auth0User.sub },\n    include: { accountCompanies: true },\n  });\n```\n\n========================================\n\nComments:\n- I can't see a auth0UserId column in your account model which you seem to be using in the query. Is it intentional?\n- in my case the issue was coming from the include, double check if `accountCompanies` is the name of your actual table?","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":96,"estimatedTokens":621}}88{"id":"stack-55002303","source":"stackoverflow","questionId":55002303,"title":"Why use Prisma in a backend environment?","tags":["graphql","prisma"],"text":"Title: Why use Prisma in a backend environment?\nTags: graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nAfter learning about GraphQL and using it in a few projects, I finally wanted to give Prisma a go. It promises to eliminate the need for a database and it generates a GraphQL client and a working database from the GraphQL Schema. So far so good.\n\nBut my question is: A GraphQL client to me really only seems useful for a client (prevent overfetching, speed up pages, React integrations, ...). Prisma however does not eliminate the need for business logic, and so one would end up using the generated client library in Node.js, just to reexport a lot of the functionality in yet another GraphQL server to the actual client.\n\nWhy should I prefer Prisma over a custom database solution? Is there a thought behind having to re-expose a lot of endpoints to the actual client?\n\n========================================\n\nTop Answer:\nEven I had similar questions when I started learning graphql. This is what I learned and realised after using it.\n\nPrisma acts as a proxy for your database providing you with a ready\nto use GraphQL API that allows you to filter and sort data along with\nsome custom types like `DateTime` which are not a part of graphql and\nyou'd have to otherwise implement yourself. It's not a GraphQL server. Just a \nlayer between your database and backend server like an ORM.\n\nIt covers almost all the possible usecases that you might have from a\ndata model with all the **CRUD** operations pre-defined in a schema\nalong with **subscriptions**, so you don't have to do all that stuff\nand focus more on your business logic side of things.\n\nAlso it removes the dependency of you writing different queries for\ndifferent databases like Sql or MongoDb acting as a layer to\ntransform it's query language to actual database queries.\n\nYou can use the API(graphql) server to expose only the desired schema\nto the client rather than everything. Since graphql queries can get\nhighly nested, it may be difficult and tricky to implement that which\nmay also lead to performance issues which is not the case in Prisma as it handles everything itself.\n\nYou can check out this article for more info.\n\n========================================\n\nCode:\n```text\nDateTime\n```\n\n========================================\n\nComments:\n- I've just sent you an email to the address I've found on your website and shared a preview of the blog post that I mentioned in my answer. I hope this addresses all your questions! Please let me know if you have any further questions. @NikxDa\n- @nburk Thanks for helping out with this! I'll be checking out the blog post tonight and I'll get back to you via mail about it. I appreciate the help! :)\n- @nburk I've dropped you a mail. Thanks for the insight! I'll edit the blog post into your answer once it is released.\n- Awesome, thanks so much for the feedback! Great to hear the article resonates with you :) Happy to help with any further questions.","metadata":{"transformedAt":"2026-08-18T18:33:14.821Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":52,"estimatedTokens":744}}89{"id":"stack-49061701","source":"stackoverflow","questionId":49061701,"title":"Upload images with apollo-upload-client in React Native","tags":["react-native","graphql","apollo","prisma"],"text":"Title: Upload images with apollo-upload-client in React Native\nTags: react-native, graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying out Prisma and React Native right now. Currently I'm trying to upload images to my db with the package _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client). But it's not going so well. \n\nCurrently I can select an image with the `ImagePicker` from Expo. And then I'm trying to do my mutation with the Apollo Client:\n\n```\nawait this.props.mutate({\n variables: {\n name,\n description,\n price,\n image,\n },\n});\n```\n\nBut I get the following error:\n\n```\nNetwork error: JSON Parse error: Unexpected identifier \"POST\"\n- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError\n- node_modules/apollo-client/bundle.umd.js:797:43 in error\n```\n\nAnd I believe it's from these lines of code:\n\n```\nconst image = new ReactNativeFile({\n uri: imageUrl,\n type: 'image/png',\n name: 'i-am-a-name',\n});\n```\n\nWhich is almost identical from the their example, https://github.com/jaydenseric/apollo-upload-client#react-native.\n\n`imageUrl` is from my state. And when I console.log `image` I get the following:\n\n```\nReactNativeFile {\n \"name\": \"i-am-a-name\",\n \"type\": \"image/png\",\n \"uri\": \"file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png\",\n}\n```\n\nSo something is popping out. But I can't get any further and I'm hoping I could get some tips from someone. \n\nI also didn't include any code from the backend since I believe the problem lays on the frontend. *But* if anyone would like to take a look at the backend I can update the question, or you could take a look here: https://github.com/Martinnord/Ecommerce-server/tree/image_uploads.\n\nThanks a lot for reading! Cheers.\n\n### Update\n\nAfter someone asked after the logic in the server I have decided to past it below:\n\n*Product.ts*\n\n```\n// import shortid from 'shortid'\nimport { createWriteStream } from 'fs'\n\nimport { getUserId, Context } from '../../utils'\n\nconst storeUpload = async ({ stream, filename }): Promise => {\n // const path = `images/${shortid.generate()}`\n const path = `images/test`\n\n return new Promise((resolve, reject) =>\n stream\n .pipe(createWriteStream(path))\n .on('finish', () => resolve({ path }))\n .on('error', reject),\n )\n }\n\nconst processUpload = async upload => {\n const { stream, filename, mimetype, encoding } = await upload\n const { path } = await storeUpload({ stream, filename })\n return path\n}\n\nexport const product = {\n async createProduct(parent, { name, description, price, image }, ctx: Context, info) {\n // const userId = getUserId(ctx)\n const userId = 1;\n console.log(image);\n const imageUrl = await processUpload(image);\n console.log(imageUrl);\n return ctx.db.mutation.createProduct(\n {\n data: {\n name,\n description,\n price,\n imageUrl,\n seller: {\n connect: { id: userId },\n },\n },\n },\n info\n )\n },\n}\n```\n\n========================================\n\nTop Answer:\nCrawling through your code, I have found this repository, which must be the front-end code if I am not mistaken?\n\nAs you've mentioned, **apollo-upload-server** requires some additional set-up and same goes for the front-end part of your project. You can find more about it here.\n\nAs far as I know, the problematic part of your code must be the initialisation of the Apollo Client. From my observation, you've put everything Apollo requires inside of `src/index` folder, but haven't included `Apollo Upload Client` itself. \n\nI have created a gist from one of my projects which initialises Apollo Upload Client alongside some other things, but I think you'll find yourself out. \n\nhttps://gist.github.com/maticzav/86892448682f40e0bc9fc4d4a3acd93a\n\nHope this helps you! 🙂\n\n========================================\n\nCode:\n```text\nawait this.props.mutate({\n  variables: {\n    name,\n    description,\n    price,\n    image,\n  },\n});\n```\n\n```text\nNetwork error: JSON Parse error: Unexpected identifier \"POST\"\n- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError\n- node_modules/apollo-client/bundle.umd.js:797:43 in error\n```\n\n```text\nconst image = new ReactNativeFile({\n  uri: imageUrl,\n  type: 'image/png',\n  name: 'i-am-a-name',\n});\n```\n\n```text\nReactNativeFile {\n  \"name\": \"i-am-a-name\",\n  \"type\": \"image/png\",\n  \"uri\": \"file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png\",\n}\n```\n\n```text\n// import shortid from 'shortid'\nimport { createWriteStream } from 'fs'\n\nimport { getUserId, Context } from '../../utils'\n\nconst storeUpload = async ({ stream, filename }): Promise<any> => {\n    // const path = `images/${shortid.generate()}`\n    const path = `images/test`\n\n    return new Promise((resolve, reject) =>\n      stream\n        .pipe(createWriteStream(path))\n        .on('finish', () => resolve({ path }))\n        .on('error', reject),\n    )\n  }\n\nconst processUpload = async upload => {\n    const { stream, filename, mimetype, encoding } = await upload\n    const { path } = await storeUpload({ stream, filename })\n    return path\n}\n\nexport const product = {\n  async createProduct(parent, { name, description, price, image }, ctx: Context, info) {\n    // const userId = getUserId(ctx)\n    const userId = 1;\n    console.log(image);\n    const imageUrl = await processUpload(image);\n    console.log(imageUrl);\n    return ctx.db.mutation.createProduct(\n      {\n        data: {\n            name,\n            description,\n            price,\n            imageUrl,\n            seller: {\n                connect: { id: userId },\n            },\n        },\n      },\n      info\n    )\n  },\n}\n```\n\n```text\nImagePicker\n```\n\n```text\nimageUrl\n```\n\n```text\nimage\n```\n\n```text\nError: Cannot use GraphQLNonNull \"User!\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.\n```\n\n```text\nsrc/index\n```\n\n```text\nApollo Upload Client\n```\n\n========================================\n\nComments:\n- Where in your server is the file uploading logic? I can't find it.\n- @marktani I have updated the question. Thanks for asking.\n- Also, most of the code behind the server side is from `graphql-yogas` example. github.com/graphcool/graphql-yoga/blob/master/examples/&hellip;\n- Thanks for your reply. I will take a closer look at your code when I get home. You said that I haven’t included Apollo Upload Link itself and I wonder if you where on the correct branch. Since on the branch image_uploads I’ve included it. Here: github.com/Martinnord/Ecommerce-app/blob/image_uploads/src/&hellip;\n- I am sorry, yes I was on the wrong branch because I thought you only had one. I will try to look into it again - hope I can find anything more useful.\n- No worries. I appriciate that you are taking your time to help me.\n- Hi, I got stuck with this apollo-upload-server stuff. I already setup correctly the client . and it send the request to apollo-server. in the server it received the 'createReadStream' but it's only an object.. how do I wrote a file from this `createReadStream()` object ?","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":256,"estimatedTokens":1981}}90{"id":"stack-50497417","source":"stackoverflow","questionId":50497417,"title":"Cascade delete related nodes using GraphQL and Prisma","tags":["graphql","cascading-deletes","prisma"],"text":"Title: Cascade delete related nodes using GraphQL and Prisma\nTags: graphql, cascading-deletes, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to figure out cascade deletion in GraphQL.\n\nI'm attempting to delete a node of type `Question`, but type `QuestionVote` has a required relation to `Question`. I'm looking for a way to delete a `Question` and all its votes at once.\n\nMutation for deleting a `Question`:\n\n```\ntype Mutation {\n deleteQuestion(where: QuestionWhereUniqueInput!): Question!\n}\n```\n\nAnd its resolver (I'm using Prisma): \n\n```\nfunction deleteQuestion(parent, args, context, info) {\n const userId = getUserId(context) \n return context.db.mutation.deleteQuestion(\n {\n where: {id: args.id}\n },\n info,\n )\n}\n```\n\nHow can I modify that mutation to also delete related `QuestionVote` nodes? Or should I add a separate mutation that deletes one or multiple instances of `QuestionVote`?\n\nIn case it's important, here are the mutations that create `Question` and `QuestionVote`:\n\n```\nfunction createQuestion(parent, args, context, info) {\n const userId = getUserId(context)\n return context.db.mutation.createQuestion(\n {\n data: {\n content: args.content,\n postedBy: { connect: { id: userId } },\n },\n },\n info,\n )\n}\n\nasync function voteOnQuestion(parent, args, context, info) {\n const userId = getUserId(context)\n\n const questionExists = await context.db.exists.QuestionVote({\n user: { id: userId },\n question: { id: args.questionId },\n })\n if (questionExists) {\n throw new Error(`Already voted for question: ${args.questionId}`)\n }\n\n return context.db.mutation.createQuestionVote(\n {\n data: {\n user: { connect: { id: userId } },\n question: { connect: { id: args.questionId } },\n },\n },\n info,\n )\n}\n```\n\nThanks!\n\n========================================\n\nCode:\n```text\ntype Mutation {\n  deleteQuestion(where: QuestionWhereUniqueInput!): Question!\n}\n```\n\n```text\nfunction deleteQuestion(parent, args, context, info) {\n  const userId = getUserId(context)  \n  return context.db.mutation.deleteQuestion(\n      {\n        where: {id: args.id}\n      },\n      info,\n  )\n}\n```\n\n```text\nfunction createQuestion(parent, args, context, info) {\n    const userId = getUserId(context)\n    return context.db.mutation.createQuestion(\n        {\n            data: {\n              content: args.content,\n              postedBy: { connect: { id: userId } },\n            },\n        },\n        info,\n    )\n}\n\nasync function voteOnQuestion(parent, args, context, info) {\n  const userId = getUserId(context)\n\n  const questionExists = await context.db.exists.QuestionVote({\n    user: { id: userId },\n    question: { id: args.questionId },\n  })\n  if (questionExists) {\n    throw new Error(`Already voted for question: ${args.questionId}`)\n  }\n\n  return context.db.mutation.createQuestionVote(\n    {\n      data: {\n        user: { connect: { id: userId } },\n        question: { connect: { id: args.questionId } },\n      },\n    },\n    info,\n  )\n}\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\nQuestion\n```\n\n```text\nQuestion\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\nQuestionVote\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\ntype Question {\n  id: ID! @unique\n  votes: [QuestionVote!]! @relation(name: \"QuestionVotes\")\n  text: String!\n}\n\ntype QuestionVote {\n  id: ID! @unique\n  question: Question @relation(name: \"QuestionVotes\")\n  isUpvote: Boolean!\n}\n```\n\n```text\ntype Question {\n  id: ID! @unique\n  votes: [QuestionVote!]! @relation(name: \"QuestionVotes\" onDelete: CASCADE)\n  text: String!\n}\n\ntype QuestionVote {\n  id: ID! @unique\n  question: Question @relation(name: \"QuestionVotes\")\n  isUpvote: Boolean!\n}\n```\n\n```text\nonCascade: DELETE\n```\n\n```text\n@relation\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\nonDelete\n```\n\n```text\nonDelete: SET_NULL\n```\n\n```text\nnull\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":223,"estimatedTokens":954}}91{"id":"stack-68874214","source":"stackoverflow","questionId":68874214,"title":"How to use connectOrCreate with many to many in prisma","tags":["database","blogs","prisma"],"text":"Title: How to use connectOrCreate with many to many in prisma\nTags: database, blogs, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to use Prisma to associate articles with tags, that is: A post has multiple tags and a tag belongs to multiple posts\n\nBut the example in Prisma will result in the creation of duplicate tags\n\nHere is my Prisma model\n\n```\nmodel Article {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n title String\n summary String\n link String @unique\n archive String\n content String\n image String\n tags Tag[]\n}\n\nmodel Tag {\n id Int @id @default(autoincrement())\n name String\n articles Article[]\n}\n```\n\nThis is my code according to the documentation, it causes duplicate tags to appear\n\n```\nawait prisma.article.create({\n data: {\n title,\n summary,\n link,\n archive,\n content,\n image,\n tags: {\n create: tags.map((tag) => ({ name: tag })),\n },\n },\n});\n```\n\nWhen I use connectOrCreate, it reports an error in many-to-many mode\n\n```\nawait prisma.article.create({\n data: {\n title,\n summary,\n link,\n archive,\n content,\n image,\n tags: {\n connectOrCreate: {\n where: tags.map((tag) => ({ name: tag })),\n create: tags.map((tag) => ({ name: tag })), \n },\n },\n },\n});\n```\n\n========================================\n\nCode:\n```text\nmodel Article {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  title     String\n  summary   String\n  link      String   @unique\n  archive   String\n  content   String\n  image     String\n  tags      Tag[]\n}\n\nmodel Tag {\n  id       Int       @id @default(autoincrement())\n  name     String\n  articles Article[]\n}\n```\n\n```js\nawait prisma.article.create({\n  data: {\n    title,\n    summary,\n    link,\n    archive,\n    content,\n    image,\n    tags: {\n      create: tags.map((tag) => ({ name: tag })),\n    },\n  },\n});\n```\n\n```js\nawait prisma.article.create({\n  data: {\n    title,\n    summary,\n    link,\n    archive,\n    content,\n    image,\n    tags: {\n      connectOrCreate: {\n        where: tags.map((tag) => ({ name: tag })),\n        create: tags.map((tag) => ({ name: tag })), \n      },\n    },\n  },\n});\n```\n\n```text\nmodel Tag {\n  id       Int       @id @default(autoincrement())\n  name     String    @unique  // change\n  articles Article[]\n}\n```\n\n```js\nawait prisma.article.create({\n  data: {\n    title,\n    summary,\n    link,\n    archive,\n    content,\n    image,\n    tags: {\n        connectOrCreate: tags.map((tag) => {\n            return {\n                where: { name: tag },\n                create: { name: tag },\n            };\n        }),\n    },\n  },\n});\n```\n\n```text\nTag.name\n```\n\n```text\nname\n```\n\n```text\nTag\n```\n\n```text\nname\n```\n\n```text\nwhere\n```\n\n```text\nconnectOrCreate\n```\n\n```text\nname\n```\n\n```text\nconnectOrCreate\n```\n\n```text\nwhere\n```\n\n```text\ncreate\n```\n\n```text\nconnectOrCreate\n```\n\n```text\nwhere\n```\n\n```text\ncreate\n```\n\n========================================\n\nComments:\n- what's the reason to use `tags.map((tag) => ({ name: tag }))` within your code ?\n- This was a lifesaver. I just want to add, since it might not be obvious by the wording, that the bullet points the author has mentioned work in tandem. It's not either or but utilizing both at the same time. This solved my issue. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":214,"estimatedTokens":805}}92{"id":"stack-77998355","source":"stackoverflow","questionId":77998355,"title":"Can't access supabase in vercel deployed product (Nextjs14)","tags":["next.js","prisma","vercel","supabase"],"text":"Title: Can't access supabase in vercel deployed product (Nextjs14)\nTags: next.js, prisma, vercel, supabase\nSource: Stack Overflow\n\nQuestion:\nI am creating web app with Nextjs14, prisma, and supabase (postgreSQL). In my localhost it works well, but I deployed it on vercel and this error happened.\n\nI did integration in vercel to connect to supabase.\n\nThe endpoints I used are here:\n\n```\nhttp://localhost:3000/api/player/attendance (for local, it works)\nhttps://*****.vercel.app/api/player/attendance (for vercel, doesn't work)\n```\n\nshema.prisma\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n```\n\n.env (I replaced my own ones)\n\n```\nDATABASE_URL=\"postgres://[db-user]:[db-password]@aws-0-[aws-region].pooler.supabase.com:5432/[db-name]\"\n```\n\nI found this article PGBouncer and IPv4 Deprecation but my url already looks like this...right? I also tried postman with this endpoint (https://*****.vercel.app/api/player/attendance) and the return was\n\n```\n{\n \"message\": \"Error\",\n \"error\": {\n \"name\": \"PrismaClientInitializationError\",\n \"clientVersion\": \"5.9.1\"\n }\n}\n```\n\nso the problem is the connection with supabase right?\n\nHere is the errors from vercel. I think that the first error makes the last two ones because I use 'map' with the data of supabase\n\n```\n[GET] /api/player/attendance status=500\n```\n\n```\nTypeError: Cannot read properties of undefined (reading 'map') at l (/var/task/.next/server/app/page.js:2:4654) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\n```\n[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] { digest: '3113241611' }\n```\n\nSo what is my problem?\n\nThanks\n\n========================================\n\nTop Answer:\nI might be appropriate one to answer this as i have spent a whole day on this.\n\nDeploying codebase which includes cloud database services you need to have **connection pool database url**. Deploying website on cloud manages database query from numerous serverless replica served from the nearest geographic location, reducing latency. refer to this for more.\n\nFollowing these would help:\n\nmake sure your project is up and running from supabase dashboard else connect if paused. It should show up like this project status image.\n\nTry resetting password before moving further by going to Project setting > configuration > Database > Database password\n\nMake sure your prisma schema looks like this:\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n directUrl = env(\"DIRECT_URL\")\n}\n```\n\nedit .env file mapping **DIRECT_URL** to primary database url one with **port 5432** used for migrations. unmark it refer this. It should look like this `postgresql://postgres:[YOUR-PASSWORD]@db.foo.supabase.co:5432/postgres`\n\nSimilarly, get database connection pool address, one with **port 6543**.\nlike this one `postgresql://postgres.foo:[YOUR-PASSWORD]@aws-0-ap-south-1.pooler.supabase.com:6543/postgres` add `?pgbouncer=true` at end to it.\n\nIt should look like this:`postgresql://postgres.foo:[YOUR-PASSWORD]@aws-0-ap-south-1.pooler.supabase.com:6543/postgres?pgbouncer=true`\n\nMake changes to vercel's build command to `npx prisma migrate deploy && next build`\n\n========================================\n\nCode:\n```text\nhttp://localhost:3000/api/player/attendance (for local, it works)\nhttps://*****.vercel.app/api/player/attendance (for vercel, doesn't work)\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n```text\nDATABASE_URL=\"postgres://[db-user]:[db-password]@aws-0-[aws-region].pooler.supabase.com:5432/[db-name]\"\n```\n\n```text\n{\n    \"message\": \"Error\",\n    \"error\": {\n        \"name\": \"PrismaClientInitializationError\",\n        \"clientVersion\": \"5.9.1\"\n    }\n}\n```\n\n```text\n[GET] /api/player/attendance status=500\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'map') at l (/var/task/.next/server/app/page.js:2:4654) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\n```text\n[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] { digest: '3113241611' }\n```\n\n```text\n?pgbouncer=true\n```\n\n```text\n5432\n```\n\n```text\n6543\n```\n\n```text\nDATABASE_URL=\"postgres://[db-user]:[db-password]@aws-0-[aws-region].pooler.supabase.com:6543/[db-name]?pgbouncer=true\"\n```\n\n```text\nbuild\n```\n\n```text\npackage.json\n```\n\n```text\n\"build\": \"prisma generate && next build\"\n```\n\n```text\nscripts\n```\n\n```text\npackage.json\n```\n\n```text\n\"postinstall\": \"prisma generate\"\n```\n\n```text\nnpx prisma generate && next build\n```\n\n```js\ndatasource db {\n    provider  = \"postgresql\"\n    url       = env(\"DATABASE_URL\")\n    directUrl = env(\"DIRECT_URL\")\n}\n```\n\n```text\npostgresql://postgres:[YOUR-PASSWORD]@db.foo.supabase.co:5432/postgres\n```\n\n```text\npostgresql://postgres.foo:[YOUR-PASSWORD]@aws-0-ap-south-1.pooler.supabase.com:6543/postgres\n```\n\n```text\n?pgbouncer=true\n```\n\n```text\npostgresql://postgres.foo:[YOUR-PASSWORD]@aws-0-ap-south-1.pooler.supabase.com:6543/postgres?pgbouncer=true\n```\n\n```text\nnpx prisma migrate deploy && next build\n```\n\n========================================\n\nComments:\n- Do you get any error logs when deploying to Vercel? If so, please include the error logs\n- @hersh yes of curse. I added errors in the descriptions. Please check it! thanks\n- Another worthwhile help page to check out: supabase.com/docs/guides/database/connecting-to-postgres/&hellip;\n- Thanks mate, my migrations were not working and this helped :-)","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":223,"estimatedTokens":1494}}93{"id":"stack-75203608","source":"stackoverflow","questionId":75203608,"title":"Nest could not find PrismaService element (this provider does not exist in the current context)","tags":["nestjs","prisma"],"text":"Title: Nest could not find PrismaService element (this provider does not exist in the current context)\nTags: nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get PrismaService on my main.ts, but it's keep crashing. I'm new on this, can anyone help me to solve it?\nMy prisma.service.ts:\n\n```\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n async onModuleInit() {\n await this.$connect();\n }\n\n async enableShutdownHooks(app: INestApplication) {\n this.$on('beforeExit', async () => {\n await app.close();\n });\n }\n}\n```\n\nMy main.ts:\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { PrismaService } from './prisma.service';\nimport { ValidationPipe } from '@nestjs/common';\nimport helmet from 'helmet';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n\n app.enableCors({\n allowedHeaders: '*',\n origin: '*',\n });\n app.use(helmet());\n app.use(helmet.hidePoweredBy());\n app.use(helmet.contentSecurityPolicy());\n\n const prismaService = app.get(PrismaService);\n await prismaService.enableShutdownHooks(app);\n\n app.useGlobalPipes(\n new ValidationPipe({\n transform: true,\n whitelist: true,\n forbidNonWhitelisted: true,\n }),\n );\n\n await app.listen(process.env.PORT, () => console.log('runing...'));\n}\nbootstrap();\n```\n\nThe error message:\n\n```\nError: Nest could not find PrismaService element (this provider does not exist in the current context)\n at InstanceLinksHost.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/instance-links-host.js:15:19)\n at NestApplication.find (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/abstract-instance-resolver.js:8:60)\n at NestApplication.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-application-context.js:64:20)\n at /home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:133:40\n at Function.run (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/errors/exceptions-zone.js:10:13)\n at Proxy. (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:132:46)\n at Proxy. (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:181:54)\n at bootstrap (/home/rafittu/wophi/alma/back/src/main.ts:18:29)\n```\n\nWhen I delete PrismaService from main.ts, server start normaly\n\n========================================\n\nTop Answer:\nAfter setting up the `PrismaService` in `prisma.service.ts` and enabling shutdown hooks in the `main.ts` file, you also need to do the following:\n\nIn the `app.module.ts` you need to add `PrismaService` as one of the providers:\n\n```\n...\nimport { PrismaService } from './prisma/prisma.service';\n\n@Module({\n imports: [],\n controllers: [AppController],\n providers: [AppService, PrismaService], // add PrismaService here\n})\nexport class AppModule {}\n```\n\n========================================\n\nCode:\n```text\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });\n  }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { PrismaService } from './prisma.service';\nimport { ValidationPipe } from '@nestjs/common';\nimport helmet from 'helmet';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  app.enableCors({\n    allowedHeaders: '*',\n    origin: '*',\n  });\n  app.use(helmet());\n  app.use(helmet.hidePoweredBy());\n  app.use(helmet.contentSecurityPolicy());\n\n  const prismaService = app.get(PrismaService);\n  await prismaService.enableShutdownHooks(app);\n\n  app.useGlobalPipes(\n    new ValidationPipe({\n      transform: true,\n      whitelist: true,\n      forbidNonWhitelisted: true,\n    }),\n  );\n\n  await app.listen(process.env.PORT, () => console.log('runing...'));\n}\nbootstrap();\n```\n\n```text\nError: Nest could not find PrismaService element (this provider does not exist in the current context)\n    at InstanceLinksHost.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/instance-links-host.js:15:19)\n    at NestApplication.find (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/abstract-instance-resolver.js:8:60)\n    at NestApplication.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-application-context.js:64:20)\n    at /home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:133:40\n    at Function.run (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/errors/exceptions-zone.js:10:13)\n    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:132:46)\n    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:181:54)\n    at bootstrap (/home/rafittu/wophi/alma/back/src/main.ts:18:29)\n```\n\n```text\napp.get(PrismaService, { strict: false })\n```\n\n```text\nstrict: false\n```\n\n```text\nAppModule\n```\n\n```js\n...\nimport { PrismaService } from './prisma/prisma.service';\n\n@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [AppService, PrismaService], // add PrismaService here\n})\nexport class AppModule {}\n```\n\n```text\nPrismaService\n```\n\n```text\nprisma.service.ts\n```\n\n```text\nmain.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\nPrismaService\n```\n\n========================================\n\nComments:\n- Using strict: false didn't work, same error message\n- Do you have a module that has `providers: [PrimsaService]` imported by the `AppModule`?\n- Sorted out!!! I have an users module and PrismaService was not imported. As I imported it, server started normaly! Thanks a lot!!","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":214,"estimatedTokens":1497}}94{"id":"stack-68601326","source":"stackoverflow","questionId":68601326,"title":"Prisma Schema Now() + 1 year","tags":["prisma"],"text":"Title: Prisma Schema Now() + 1 year\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nWhen defining a schema in prisma, providing now() as default datetime field value is possible.\n\nIs it possible to provide now()+ 1 year as default ?\n\nAll my attemps have failed.\n\n========================================\n\nCode:\n```text\nmodel foo {\n  id Int @id\n  createdAt DateTime @default(dbgenerated(\"NOW() + interval '1 year'\"))   // Default value is 1 year from now. \n\n  // ... other fields\n}\n```\n\n========================================\n\nComments:\n- I do think you have to write a database trigger, at least in MySQL, when you want a different default value for a datetime column then `now()`.\n- And with Mysql, do you know if it is possible?\n- can someone link the docs for this or some blog post?\n- found it!! date time functions and operations this is only for Postgres but others should have sth like it as well","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":30,"estimatedTokens":226}}95{"id":"stack-65162657","source":"stackoverflow","questionId":65162657,"title":"One-to-many self-relation in prisma schema","tags":["database","prisma"],"text":"Title: One-to-many self-relation in prisma schema\nTags: database, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to create a simple table:\n\n```\nUsers\n---\nid\nname\nfriends\n```\n\n`friends` field should be an array of other user ids. I'm trying to define a schema for this in `schema.prisma`:\n\n```\nmodel User {\n id String @id @default(uuid())\n name String\n friends User[]\n}\n```\n\nSaving the file autocompletes the schema to this:\n\n```\nmodel User {\n id String @id @default(uuid())\n name String\n friends User[] @relation(\"UserToUser\")\n User User? @relation(\"UserToUser\", fields: [userId], references: [id])\n userId String?\n}\n```\n\nI'm not sure how to interpret this. I have read the Prisma docs about one-to-many self relations, but since it states\n\nThis relation expresses the following:\n\n- \"a user has zero or one teachers\"\n\n- \"a user can have zero or more students\"\n\nI doubt it's what I want. How do I get the \"a user can have zero or more students\" without the \"a user has zero or one teachers\" part?\n\n========================================\n\nCode:\n```text\nUsers\n---\nid\nname\nfriends\n```\n\n```text\nmodel User {\n  id      String  @id @default(uuid())\n  name    String\n  friends User[]\n}\n```\n\n```text\nmodel User {\n  id      String  @id @default(uuid())\n  name    String\n  friends User[]  @relation(\"UserToUser\")\n  User    User?   @relation(\"UserToUser\", fields: [userId], references: [id])\n  userId  String?\n}\n```\n\n```text\nfriends\n```\n\n```text\nschema.prisma\n```\n\n```text\nmodel User {\n  id              String @id @default(uuid())\n  name            String\n  friends         User[] @relation(\"friends\")\n  friendsRelation User[] @relation(\"friends\")\n}\n```\n\n```text\nawait prisma.user.create({\n    data: {\n      name: 'user 1',\n      friends: { create: [{ name: 'user 2' }, { name: 'user 3' }] },\n    },\n  })\n```\n\n```text\nawait prisma.user.findMany({ include: { friends: true } })\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nUsers\n```\n\n```text\nfriendsRelation\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- Thank you! Understanding that I need many-to-many relationship instead of one-to-many made it \"click\"\n- how would I select the root node from this model?","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":135,"estimatedTokens":551}}96{"id":"stack-72412037","source":"stackoverflow","questionId":72412037,"title":"How can I use the Prisma adapter for Next-Auth without email and emailVerified values","tags":["next.js","prisma","next-auth"],"text":"Title: How can I use the Prisma adapter for Next-Auth without email and emailVerified values\nTags: next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI am using next-auth with a custom provider and the Prisma adapter and I only want to store the values: id, name, country, avatar, and gender. However, I am getting this error:\n\n```\n[next-auth][error][adapter_error_createUser] \nhttps://next-auth.js.org/errors#adapter_error_createuser\nInvalid `p.user.create()` invocation in\n.\\node_modules\\@next-auth\\prisma-adapter\\dist\\index.js:6:38\n\n 3 exports.PrismaAdapter = void 0;\n 4 function PrismaAdapter(p) {\n 5 return {\n→ 6 createUser: (data) => p.user.create({\n data: {\n name: [redacted],\n wcaId: [redacted],\n country: [redacted],\n avatar: [redacted],\n gender: [redacted],\n email: undefined,\n emailVerified: null\n ~~~~~~~~~~~~~\n }\n })\n\nUnknown arg `emailVerified` in data.emailVerified for type UserCreateInput. Available args:\n...\n```\n\nThe profile object in my custom provider looks like this:\n\n```\nprofile(profile) {\n return {\n id: profile.me.id,\n name: profile.me.name,\n country: profile.me.country_iso2,\n avatar: profile.me.avatar.url,\n gender: profile.me.gender,\n };\n },\n```\n\nEverything in my Prisma schema follows the example in https://next-auth.js.org/adapters/prisma#setup except the User model which is like so:\n\n```\nmodel User {\n id String @id @default(cuid())\n name String\n country String @db.Char(2)\n avatar String\n gender String @db.Char(1)\n accounts Account[]\n sessions Session[]\n // Temporary workaround:\n email String? @unique\n emailVerified DateTime? @map(\"email_verified\")\n}\n```\n\nIn the error, the adapter appears to have added email and emailVerified to the data object so the temporary workaround I am using is adding email and emailVerified columns to my Prisma model as shown above. However, this is not ideal, and I would like to know how I can remove these unnecessary columns from my database as their values are always undefined and null.\n\n========================================\n\nCode:\n```text\n[next-auth][error][adapter_error_createUser] \nhttps://next-auth.js.org/errors#adapter_error_createuser\nInvalid `p.user.create()` invocation in\n.\\node_modules\\@next-auth\\prisma-adapter\\dist\\index.js:6:38\n\n  3 exports.PrismaAdapter = void 0;\n  4 function PrismaAdapter(p) {\n  5     return {\n→ 6         createUser: (data) => p.user.create({\n              data: {\n                name: [redacted],\n                wcaId: [redacted],\n                country: [redacted],\n                avatar: [redacted],\n                gender: [redacted],\n                email: undefined,\n                emailVerified: null\n                ~~~~~~~~~~~~~\n              }\n            })\n\nUnknown arg `emailVerified` in data.emailVerified for type UserCreateInput. Available args:\n...\n```\n\n```text\nprofile(profile) {\n    return {\n      id: profile.me.id,\n      name: profile.me.name,\n      country: profile.me.country_iso2,\n      avatar: profile.me.avatar.url,\n      gender: profile.me.gender,\n    };\n  },\n```\n\n```text\nmodel User {\n  id            String    @id @default(cuid())\n  name          String\n  country       String    @db.Char(2)\n  avatar        String\n  gender        String    @db.Char(1)\n  accounts      Account[]\n  sessions      Session[]\n  // Temporary workaround:\n  email         String?   @unique\n  emailVerified DateTime? @map(\"email_verified\")\n}\n```\n\n```text\nconst prismaAdapter = PrismaAdapter(prisma);\n\n//@ts-ignore\nprismaAdapter.createUser = (data: User) => {\n  return prisma.user.create({\n    data: {\n      name: data.name as string,\n      email: data.email as string,\n\n    },\n  })\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.822Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":136,"estimatedTokens":905}}97{"id":"stack-70250565","source":"stackoverflow","questionId":70250565,"title":"Prisma update with relation in WHERE property","tags":["sql","prisma"],"text":"Title: Prisma update with relation in WHERE property\nTags: sql, prisma\nSource: Stack Overflow\n\nQuestion:\nGiven these schemas:\n\n```\nmodel awayinfo {\nPlayerID Int @id\nIsAway Boolean\nplayerinfo playerinfo @relation(fields: [PlayerID], references: [ID])\n}\n \nmodel playerinfo {\nname String @db.VarChar(15)\nID Int @id @unique @default(autoincrement())\nawayinfo awayinfo?\n}\n```\n\n**How would I create a prisma SQL update for the awayinfo table if the only identifier I have would be the Name of a player and not the ID?**\n\nwhat I tried:\n\nI try to pass something into the WHERE part as seen below:\n\n```\nconst result = await prisma.awayinfo.update({\n where: {\n PlayerID: {\n name: name\n }\n },\n data: {\n IsAway: true,\n }\n });\n```\n\nbut it always gives me the Error:\n\n```\nInvalid `prisma.awayinfo.update()` invocation: \n\nArgument PlayerID: Got invalid value\n{\n name: 'Dummy'\n\n}\non prisma.updateOneawayinfo. Provided Json, expected Int.\n```\n\nI got pretty desperate and even tried wonky selects like this one\n\n```\nconst result = await prisma.awayinfo.update({\n where: {\n PlayerID: {\n playerinfo: {\n Where: {\n name: name\n },\n select: {ID: true},\n }}\n }, .....\n```\n\nbut obviously this would not work aswell.\nI wonder what I am missing here and I cannot find any example of a condition within the WHERE clause in the prisma documentation\n\n========================================\n\nTop Answer:\n**Alternative:** call `updateMany` instead of `update`\n\nIn prisma `update` function expects a where condition that uniquely identifies a single record.\n\nHence either fetch records using `updateMany` or put name unique.\n\nAlthough you cannot select or include anything with `updateMany`.\n\n========================================\n\nCode:\n```text\nmodel awayinfo {\nPlayerID   Int        @id\nIsAway     Boolean\nplayerinfo playerinfo @relation(fields: [PlayerID], references: [ID])\n}\n    \nmodel playerinfo {\nname       String    @db.VarChar(15)\nID         Int       @id @unique @default(autoincrement())\nawayinfo   awayinfo?\n}\n```\n\n```text\nconst result = await prisma.awayinfo.update({\n    where: {\n      PlayerID: {\n        name: name\n      }\n  },\n    data: {\n      IsAway: true,\n    }\n  });\n```\n\n```text\nInvalid `prisma.awayinfo.update()` invocation: \n\nArgument PlayerID: Got invalid value\n{\n  name: 'Dummy'\n\n}\non prisma.updateOneawayinfo. Provided Json, expected Int.\n```\n\n```text\nconst result = await prisma.awayinfo.update({\n    where: {\n      PlayerID: {\n      playerinfo: {\n        Where: {\n        name: name\n      },\n      select: {ID: true},\n    }}\n  }, .....\n```\n\n```text\nmodel playerinfo {\n  name     String    @unique @db.VarChar(15)\n  ID       Int       @id @unique @default(autoincrement())\n  awayinfo awayinfo?\n}\n```\n\n```js\nconst data = await prisma.playerinfo.update({\n    where: {\n        name: name\n    }, \n    data: {\n        awayinfo: {\n            update: {\n                IsAway: true\n            }\n        }\n    }\n})\n```\n\n```text\nname\n```\n\n```text\nplayerinfo\n```\n\n```text\nname\n```\n\n```text\nunique\n```\n\n```text\nname\n```\n\n```text\nwhere\n```\n\n```text\nplayerinfo\n```\n\n```text\nupdateMany\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n```text\nupdateMany\n```\n\n```text\nupdateMany\n```\n\n========================================\n\nComments:\n- This answer is very detailed and solved the problem completly. I figured the unique part out myself but thank you again for pointing that out aswell!\n- Welcome! Happy to help :D\n- i feel like this is a good alternative as well if we want to keep the `prisma.awayInfo.update` instead of the `prisma.playerInfo.update` but might be misleading when reading the code and seing `updateMany` when in fact we only mean to update one row","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":213,"estimatedTokens":913}}98{"id":"stack-69564787","source":"stackoverflow","questionId":69564787,"title":"NestJS Postgres Prisma - Error type 'string' is not assignable to parameter type 'TemplateStringsArray | Sql'","tags":["node.js","typescript","postgresql","nestjs","prisma"],"text":"Title: NestJS Postgres Prisma - Error type 'string' is not assignable to parameter type 'TemplateStringsArray | Sql'\nTags: node.js, typescript, postgresql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a NestJS Monorepo service using Microservices architecture with PostgreSQL as a database, Prisma as ORM and TypeScript as primary language.\nBut I keep getting the error below when I try executing a Postgres query.\n\nsrc/infrastructure/persistence/work.repository.postgres.ts:188:7 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray | Sql'.\n\nI checked the data types and they seem to be compatible.\n\nPlease help me fix this.\n\nStack: TypeScript, PostgreSQL, Node.JS, Express and NestJS.\n\nThanks in advance!\n\n```\nasync findWriterNumber(writerAddress: string): Promise {\n const maxNumber = await this.prismaService.$queryRaw(\n `SELECT coalesce(max('writerNumber') + 1, 0) as max\n FROM \"Work\"\n LEFT OUTER JOIN \"WriterID\"\n ON \"Work\".\"id\" = \"WorkID\".\"workId\" AND \"WorkID\".\"address\" = '${writerAddress}'`,\n );\n return maxNumber[0].max;\n }\n```\n\n========================================\n\nTop Answer:\nAnother solution is to use the `Prisma.sql` helper:\n\n```\nconst maxNumber = await this.prismaService.$queryRaw(\n Prisma.sql`SELECT coalesce(max('writerNumber') + 1, 0) as max\n FROM \"Work\"\n LEFT OUTER JOIN \"WriterID\"\n ON \"Work\".\"id\" = \"WorkID\".\"workId\"\n AND \"WorkID\".\"address\" = '${writerAddress}'`,\n);\nreturn maxNumber[0].max;\n```\n\n========================================\n\nCode:\n```js\nasync findWriterNumber(writerAddress: string): Promise<number> {\n    const maxNumber = await this.prismaService.$queryRaw<{\n      max: number;\n    }>(\n      `SELECT coalesce(max('writerNumber') + 1, 0) as max\n       FROM \"Work\"\n                LEFT OUTER JOIN \"WriterID\"\n                                ON \"Work\".\"id\" = \"WorkID\".\"workId\" AND \"WorkID\".\"address\" = '${writerAddress}'`,\n    );\n    return maxNumber[0].max;\n  }\n```\n\n```js\nasync findWriterNumber(writerAddress: string): Promise<number> {\n    const maxNumber = await this.prismaService.$queryRaw<{\n      max: number;\n    }>\n      `SELECT coalesce(max('writerNumber') + 1, 0) as max\n       FROM \"Work\"\n                LEFT OUTER JOIN \"WriterID\"\n                                ON \"Work\".\"id\" = \"WorkID\".\"workId\" AND \"WorkID\".\"address\" = '${writerAddress}'`;\n    return maxNumber[0].max;\n  }\n```\n\n```text\nconst maxNumber = await this.prismaService.$queryRaw<{ max: number; }>(\n  Prisma.sql`SELECT coalesce(max('writerNumber') + 1, 0) as max\n   FROM \"Work\"\n   LEFT OUTER JOIN \"WriterID\"\n   ON \"Work\".\"id\" = \"WorkID\".\"workId\"\n   AND \"WorkID\".\"address\" = '${writerAddress}'`,\n);\nreturn maxNumber[0].max;\n```\n\n```text\nPrisma.sql\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":685}}99{"id":"stack-65459703","source":"stackoverflow","questionId":65459703,"title":"Querying many-to-many relations via associative table with Prisma","tags":["prisma"],"text":"Title: Querying many-to-many relations via associative table with Prisma\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI'm new to Prisma and while it's been incredibly easy to pick up so far, I'm running into a problem that I can't seem to find a good answer to. I've read through the docs about relation queries, but from my understanding Prisma doesn't have any support for many-to-many via fluent api. Every query must return a single entity and then you can add the related table, but in my case my query will return many entities that I then would like to join on.\n\nHere's a quick example of my schema:\n\n```\nmodel User {\n id String @id @default(uuid())\n}\n\nmodel Workspace {\n id String @id @default(uuid())\n}\n\nmodel WorkspaceUser {\n workspace Workspace @relation(fields: [workspaceId], references: [id])\n workspaceId String\n user User @relation(fields: [userId], references: [id])\n userId String\n}\n```\n\nI was hoping to do something like:\n\n```\nawait prisma.workspaceUser.findMany({\n where: { userId: \"123\" },\n}).workspaces();\n```\n\nAlso, I noticed that intellisense shows there is a .join() method, but it's not mentioned in the docs.\n\nDoes Prisma offer a solution to this problem, or should I use `$queryRaw`?\n\n========================================\n\nCode:\n```text\nmodel User {\n  id String @id @default(uuid())\n}\n\n\nmodel Workspace {\n  id String  @id @default(uuid())\n}\n\nmodel WorkspaceUser {\n  workspace   Workspace @relation(fields: [workspaceId], references: [id])\n  workspaceId String\n  user        User @relation(fields: [userId], references: [id])\n  userId      String\n}\n```\n\n```text\nawait prisma.workspaceUser.findMany({\n  where: { userId: \"123\" },\n}).workspaces();\n```\n\n```text\n$queryRaw\n```\n\n```text\nawait prisma.workspaceUser.findUnique({\n  where: { userId: \"123\" },\n}).workspace();\n```\n\n```text\nconst allRecords = await prisma.workspaceUser.findMany({\n  where: { userId: \"123\" },\n  include: {workspace: true},\n});\n```\n\n```text\ninclude\n```\n\n```text\nallRecords[i].workspace;\n```\n\n========================================\n\nComments:\n- This took me an unnecessary amount of time to realize. Thank you ! Additionally, is there a way to continue populating the relations of the tables you include? In your code above, lets say workspace has a relation to another table too\n- yes you keep nesting the `include` statements or `select` statements\n- @AdamJames there is a easy way to resollve this case? I want the response will be this => Response: User { ......., workspaces: Workspace[] (only filter by id from woorkspaceuser tablle) }","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":96,"estimatedTokens":636}}100{"id":"stack-72433347","source":"stackoverflow","questionId":72433347,"title":"How to fix \"createMany does not exists...\" in prisma?","tags":["prisma"],"text":"Title: How to fix \"createMany does not exists...\" in prisma?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI'm planning to create a seeder for my `projects` table. I'm using `createMany` to insert multiple data in just a query (see code below). But the problem is, it does not recognize `createMany` and throws and error after running a jest test.\n\nAnother thing that is confusing me, there was no typescript error in my code. And I can create also single data using `create` function.\n\nI already been to prisma documentation, but I can't determine what was wrong in my code. Could someone help me figure it out. (comments would also help).\n\nerror TS2339: Property 'createMany' does not exist on type 'ProviderDelegate'.\n\n**schema.prisma**\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"sqlite\"\n url = \"file:./dev.db\"\n}\n\nmodel Provider {\n id Int @id @default(autoincrement())\n user_id Int\n name String\n space_key String\n api_key String\n projects Project[]\n created_at DateTime @default(now())\n updated_at DateTime @updatedAt\n @@unique([user_id, api_key])\n}\n```\n\n**my usage**\n\n```\nimport { PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n\n...\n\nawait prisma.provider.createMany({\n data: [\n {\n user_id: 1,\n name: 'Nicole Sal',\n space_key: 'nic_spa',\n api_key: 'nic_api',\n created_at: new Date(),\n updated_at: new Date()\n },\n // ... more data here (same at above)\n ]\n})\n```\n\n========================================\n\nTop Answer:\nUpdate: Prisma now supports createMany on SQLite, see https://www.prisma.io/docs/orm/reference/prisma-client-reference#createmany\n\nHowever, note that:\n\nYou cannot create or connect relations by using nested create,\ncreateMany, connect, connectOrCreate queries inside a top-level\ncreateMany() query.\n\nIf this is why you aren't seeing the function, there's good news:\n\nYou can use a nested a createMany query inside an update() or create() query - for example, add a User and two Post records with a nested createMany at the same time.\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"sqlite\"\n  url      = \"file:./dev.db\"\n}\n\nmodel Provider {\n  id Int @id @default(autoincrement())\n  user_id Int\n  name String\n  space_key String\n  api_key String\n  projects Project[]\n  created_at DateTime @default(now())\n  updated_at DateTime @updatedAt\n  @@unique([user_id, api_key])\n}\n```\n\n```text\nimport { PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n\n...\n\nawait prisma.provider.createMany({\n  data: [\n    {\n      user_id: 1,\n      name: 'Nicole Sal',\n      space_key: 'nic_spa',\n      api_key: 'nic_api',\n      created_at: new Date(),\n      updated_at: new Date()\n    },\n    // ... more data here (same at above)\n  ]\n})\n```\n\n```text\nprojects\n```\n\n```text\ncreateMany\n```\n\n```text\ncreateMany\n```\n\n```text\ncreate\n```\n\n```text\ncreateMany\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":142,"estimatedTokens":733}}101{"id":"stack-75735106","source":"stackoverflow","questionId":75735106,"title":"Prevent Prisma data loss in production when migrate schema?","tags":["node.js","typescript","postgresql","prisma"],"text":"Title: Prevent Prisma data loss in production when migrate schema?\nTags: node.js, typescript, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm confused about the development team workflow for development to production database migrations. The docs are pretty decent but there's some gaps in my mind about the proper way to do a production deploy without data loss.\n\nMy thought is why would dropping data in development ever be acceptable, because you'll end up with a migration script that will fail in production (because `prisma migrate deploy` never drops data but fails instead.. correct or can it???).\n\nWhat is the proper dev to prod team convention for Prisma migrations? This is my thinking:\n\n- Use `db push` locally; NEVER accept data loss\n\n- When happy with schema changes, run `migrate dev --create-only`\n\n- Adjust migration scripts to avoid data loss; if data loss is necessary, change the SQL so it creates temporary tables to move the data while schema is changed, then move data back?\n\n- Run `migrate dev` locally to apply migrations to local database; NEVER accept data loss\n\n- Deploy code and run `migrate deploy` in production\n\nIs this best practices or is there a better way to do this? I don't see why migrations that require dropped data should ever make it into source control, but maybe I'm missing something. Any help or experience would be greatly appreciated!\n\n========================================\n\nCode:\n```text\nprisma migrate deploy\n```\n\n```text\ndb push\n```\n\n```text\nmigrate dev --create-only\n```\n\n```text\nmigrate dev\n```\n\n```text\nmigrate deploy\n```\n\n```text\ndb push\n```\n\n```text\nprisma migrate dev\n```\n\n```text\nprisma migrate dev\n```\n\n```text\ngit commit -m\n```\n\n```text\nprisma migrate dev --create-only\n```\n\n```text\nSQL\n```\n\n```text\nprisma migrate dev\n```\n\n```text\nmigrations\n```\n\n```text\nprisma migrate deploy\n```\n\n```text\nprisma migrate dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":85,"estimatedTokens":472}}102{"id":"stack-69178675","source":"stackoverflow","questionId":69178675,"title":"Prisma increase count by 1 after Find query","tags":["next.js","prisma"],"text":"Title: Prisma increase count by 1 after Find query\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to count how many times a record was viewed by users by managing a field called `views` in the table. I want to increase the count every time a record is pulled to be sent by the API.\n\nWhat's the right and fastest way to do it while not blocking the thread to return the data to the frontend.\n\nStack: NextJS and Prisma\n\n========================================\n\nCode:\n```text\nviews\n```\n\n```text\nawait prisma.model.update({\n  where: { id: 'some-id' },\n  data: { value: { increment: 1 } }\n})\n```\n\n========================================\n\nComments:\n- thanks. a modified version of this worked.","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":29,"estimatedTokens":178}}103{"id":"stack-74922004","source":"stackoverflow","questionId":74922004,"title":"Prisma Studio: The column `(not available)` does not exist in the current database","tags":["prisma"],"text":"Title: Prisma Studio: The column `(not available)` does not exist in the current database\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI got this error while working with Prisma, my solution is below.\n\nI just want to post a solution, I don't have a question anymore. I need to keep typing this in order to meet Stack Overflow quality stnadards.\n\n========================================\n\nComments:\n- And don't forget to stop and restart the server to see the new model reflected!\n- I am getting this error though I've pushed/migrated my prisma schema and also restarted my app process but still the same error. It's throwing this error in vitest though and not in application","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":14,"estimatedTokens":170}}104{"id":"stack-71231246","source":"stackoverflow","questionId":71231246,"title":"prisma generate throws TypeError: collection is not iterable","tags":["typescript","prisma","prisma2"],"text":"Title: prisma generate throws TypeError: collection is not iterable\nTags: typescript, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm using typescript w/ prisma and when I try to run `prisma generate`, it keeps throwing\n\n```\nTypeError: collection is not iterable.\n at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21)\n at Object.getTypeMap (/node_modules/@prisma/client/generator-build/index.js:59468:17)\n at new DMMFHelper (/node_modules/@prisma/client/generator-build/index.js:59365:25)\n at new TSClient (/node_modules/@prisma/client/generator-build/index.js:60630:17)\n at buildClient (/node_modules/@prisma/client/generator-build/index.js:60876:18)\n at generateClient (/node_modules/@prisma/client/generator-build/index.js:60947:47)\n at async LineStream. (/node_modules/@prisma/client/generator-build/index.js:54186:24)\n```\n\nI think there's something wrong with the setting but can't find a specific reason why.\n\nMy prisma version is 3.9.2, @prisma/client is 3.10.0, and using mac os\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n /* Language and Environment */\n \"target\": \"es2018\",\n\n /* Modules */\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n\n /* Emit */\n \"outDir\": \"./build\",\n \"rootDir\": \"./src\",\n \"esModuleInterop\": true,\n \"forceConsistentCasingInFileNames\": true,\n\n /* Type Checking */\n \"strict\": true,\n \"skipLibCheck\": true\n },\n \"include\": [\"src/**/*\"],\n \"exclude\": [\"node_modules\"]\n}\n```\n\npackage.json\n\n```\n{\n \"scripts\": {\n \"dev\": \"nodemon --watch \\\"src/**/*.ts\\\" --exec \\\"ts-node\\\" src/app.ts\",\n \"build\": \"tsc -p tsconfig.json\",\n \"start\": \"node build/app.js\",\n \"prepare\": \"husky install\",\n \"lint-staged\": \"lint-staged\"\n },\n \"author\": \"\",\n \"license\": \"MIT\",\n \"lint-staged\": {\n \"src/**/*.{ts,tsx}\": [\n \"eslint --fix\",\n \"prettier --write\"\n ]\n },\n \"husky\": {\n \"hooks\": {\n \"pre-commit\": \"lint-staged\"\n }\n },\n \"prisma\": {\n \"schema\": \"src/prisma/schema.prisma\"\n },\n \"dependencies\": {\n \"@prisma/client\": \"^3.10.0\",\n \"@types/morgan\": \"^1.9.3\",\n \"aws-sdk\": \"^2.1077.0\",\n \"cors\": \"^2.8.5\",\n \"dotenv\": \"^16.0.0\",\n \"express\": \"^4.17.3\",\n \"mysql\": \"^2.18.1\",\n \"prisma\": \"^3.9.2\"\n },\n \"devDependencies\": {\n \"@types/cors\": \"^2.8.12\",\n \"@types/express\": \"^4.17.13\",\n \"@types/mysql\": \"^2.15.21\",\n \"@types/node\": \"^17.0.18\",\n \"@typescript-eslint/eslint-plugin\": \"^5.12.0\",\n \"@typescript-eslint/parser\": \"^5.12.0\",\n \"eslint\": \"^8.9.0\",\n \"eslint-config-prettier\": \"^8.4.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"husky\": \"^7.0.0\",\n \"lint-staged\": \"^12.3.4\",\n \"prettier\": \"^2.5.1\",\n \"ts-node\": \"^10.5.0\",\n \"typescript\": \"^4.5.5\"\n }\n}\n```\n\nSOLVED IT!\n\nI just re-installed Prisma in devdependency and it worked fine.\n\n========================================\n\nCode:\n```text\nTypeError: collection is not iterable.\n at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21)\n    at Object.getTypeMap (/node_modules/@prisma/client/generator-build/index.js:59468:17)\n    at new DMMFHelper (/node_modules/@prisma/client/generator-build/index.js:59365:25)\n    at new TSClient (/node_modules/@prisma/client/generator-build/index.js:60630:17)\n    at buildClient (/node_modules/@prisma/client/generator-build/index.js:60876:18)\n    at generateClient (/node_modules/@prisma/client/generator-build/index.js:60947:47)\n    at async LineStream.<anonymous> (/node_modules/@prisma/client/generator-build/index.js:54186:24)\n```\n\n```text\n{\n  \"compilerOptions\": {\n    /* Language and Environment */\n    \"target\": \"es2018\",\n\n    /* Modules */\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n\n    /* Emit */\n    \"outDir\": \"./build\",\n    \"rootDir\": \"./src\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n\n    /* Type Checking */\n    \"strict\": true,\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\n{\n  \"scripts\": {\n    \"dev\": \"nodemon --watch \\\"src/**/*.ts\\\" --exec \\\"ts-node\\\" src/app.ts\",\n    \"build\": \"tsc -p tsconfig.json\",\n    \"start\": \"node build/app.js\",\n    \"prepare\": \"husky install\",\n    \"lint-staged\": \"lint-staged\"\n  },\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"lint-staged\": {\n    \"src/**/*.{ts,tsx}\": [\n      \"eslint --fix\",\n      \"prettier --write\"\n    ]\n  },\n  \"husky\": {\n    \"hooks\": {\n      \"pre-commit\": \"lint-staged\"\n    }\n  },\n  \"prisma\": {\n    \"schema\": \"src/prisma/schema.prisma\"\n  },\n  \"dependencies\": {\n    \"@prisma/client\": \"^3.10.0\",\n    \"@types/morgan\": \"^1.9.3\",\n    \"aws-sdk\": \"^2.1077.0\",\n    \"cors\": \"^2.8.5\",\n    \"dotenv\": \"^16.0.0\",\n    \"express\": \"^4.17.3\",\n    \"mysql\": \"^2.18.1\",\n    \"prisma\": \"^3.9.2\"\n  },\n  \"devDependencies\": {\n    \"@types/cors\": \"^2.8.12\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/mysql\": \"^2.15.21\",\n    \"@types/node\": \"^17.0.18\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.12.0\",\n    \"@typescript-eslint/parser\": \"^5.12.0\",\n    \"eslint\": \"^8.9.0\",\n    \"eslint-config-prettier\": \"^8.4.0\",\n    \"eslint-plugin-prettier\": \"^4.0.0\",\n    \"husky\": \"^7.0.0\",\n    \"lint-staged\": \"^12.3.4\",\n    \"prettier\": \"^2.5.1\",\n    \"ts-node\": \"^10.5.0\",\n    \"typescript\": \"^4.5.5\"\n  }\n}\n```\n\n```text\nprisma generate\n```\n\n```text\nyarn add prisma@latest / npm i prisma@latest\nyarn add @prisma/client@latest / npm i @prisma/client@latest\n```\n\n========================================\n\nComments:\n- I just tried with your setup and it worked fine for me. To confirm you are getting this error when executing `npx prisma generate` right?\n- I solved it by re-install Prisma with devdependency. I think error was generated while building maybe...? Anyway thanks for the comment\n- I needed this too. It makes me wonder how it was ever working before.","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":217,"estimatedTokens":1397}}105{"id":"stack-67976986","source":"stackoverflow","questionId":67976986,"title":"Prisma DATABASE_URL error (Cloud Run + Cloud SQL)","tags":["google-cloud-sql","google-cloud-run","prisma"],"text":"Title: Prisma DATABASE_URL error (Cloud Run + Cloud SQL)\nTags: google-cloud-sql, google-cloud-run, prisma\nSource: Stack Overflow\n\nQuestion:\nI use Prisma with Cloud Run & Cloud SQL. After providing `DATABASE_URL` to the `prisma.schema` it throws me an error in runtime.\n\n```\nCan't reach database server at `(/cloudsql/project-name:us-east1:database-id)`:`5432`\nPlease make sure your database server is running at `(/cloudsql/project-name:us-east1:database-id)`:`5432`.\"\n```\n\n- Database: Postgres\n\n- Provided url `DATABASE_URL`: `postgresql://username:password@localhost/databasename?host=(/cloudsql/project-name:us-east1:database-id)`\n\nWhat is wrong with connection? Do I failed to construct `DATABASE_URL` correctly?\n\n========================================\n\nCode:\n```text\nCan't reach database server at `(/cloudsql/project-name:us-east1:database-id)`:`5432`\nPlease make sure your database server is running at `(/cloudsql/project-name:us-east1:database-id)`:`5432`.\"\n```\n\n```text\nDATABASE_URL\n```\n\n```text\nprisma.schema\n```\n\n```text\nDATABASE_URL\n```\n\n```text\npostgresql://username:password@localhost/databasename?host=(/cloudsql/project-name:us-east1:database-id)\n```\n\n```text\nDATABASE_URL\n```\n\n```text\npostgresql://username:password@localhost/databasename?host=(/cloudsql/project-name:us-east1:database-id)\n```\n\n```text\npostgresql://username:password@localhost/databasename?host=/cloudsql/project-name:us-east1:database-id\n```\n\n```text\n()\n```\n\n```text\nhost\n```\n\n```text\n/cloudsql/project-name:us-east1:database-id\n```\n\n========================================\n\nComments:\n- Show your Cloud Run deployment and the deployment command.\n- @JohnHanley I was able to manage this issue on my own. The problem was in brackets around the `host` parameter in the connection URL. I posted my solution as an answer to the question.\n- For anyone who still has an error, my issue was incorrectly trying to connect to the \"postgres\" database. Create a new database for application data as suggested here","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":72,"estimatedTokens":498}}106{"id":"stack-72282755","source":"stackoverflow","questionId":72282755,"title":"Prisma Mongodb can't create a user model","tags":["mongodb","next.js","prisma"],"text":"Title: Prisma Mongodb can't create a user model\nTags: mongodb, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\n**So I am using Prisma for the first time and my provider is `mongodb` and when I want to create a model it throws me an error**\n\n```\nInvalid `prisma.user.create()` invocation:\n\n Prisma needs to perform transactions, which requires your MongoDB server to be run \nas a replica set. https://pris.ly/d/mongodb-replica-set\n```\n\n**I am using Prisma in a nextjs app and I put the code inside the API pages**\n\nMy DATABASE_URL is `mongodb://localhost:27017/threadzees`\n\nCode :\n\n```\nawait prisma.user.create({\n data: {\n username,\n email,\n avatar: \"1\",\n createdAt: new Date(),\n },\n });\n```\n\n**How do I fix this issue?**\n\n========================================\n\nTop Answer:\nIf you are using the local mongodb service, locate the mongod.cfg file (usually in `Program File\\MongoDB\\Server\\[version number]\\bin`) and configure it to use replica set. Add the following lines:\n\n```\nreplication:\n replSetName: rs0\n```\n\nThen launch `mongosh` from a terminal and initiate the replica set servers using `rs.initiate()`. Your code should be working fine now.\n\nPS:\n\n- For unix systems you can find `mongod.conf` in `/etc/` directory.\n\n- For MacOS if installed mongo using brew you can find it in `/opt/homebrew/etc/`\n\n========================================\n\nCode:\n```text\nInvalid `prisma.user.create()` invocation:\n\n\n  Prisma needs to perform transactions, which requires your MongoDB server to be run \nas a replica set. https://pris.ly/d/mongodb-replica-set\n```\n\n```js\nawait prisma.user.create({\n      data: {\n        username,\n        email,\n        avatar: \"1\",\n        createdAt: new Date(),\n      },\n    });\n```\n\n```text\nmongodb\n```\n\n```text\nmongodb://localhost:27017/threadzees\n```\n\n```text\n# Open new terminal execute below command\n mongod --port=27001 --dbpath=. --replSet=rs0\n# Open another terminal window execute below command\nmongo.exe\n# Then below command\nrs.initiate( {    _id : \"rs0\", members: [ { _id: 0, host: \"localhost:27001\" } ] })\n# your new connection String\nmongodb://localhost:27001\n```\n\n```text\nreplication:\n   replSetName: rs0\n```\n\n```text\nProgram File\\MongoDB\\Server\\[version number]\\bin\n```\n\n```text\nmongosh\n```\n\n```text\nrs.initiate()\n```\n\n```text\nmongod.conf\n```\n\n```text\n/etc/\n```\n\n```text\n/opt/homebrew/etc/\n```\n\n```text\nmongodb://127.0.0.1:27017/threadzees\n```\n\n========================================\n\nComments:\n- use cloud based Mongo is best .thanks\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":130,"estimatedTokens":690}}107{"id":"stack-67923628","source":"stackoverflow","questionId":67923628,"title":"How to handle conditional prepared statements using prisma and postgresql?","tags":["node.js","postgresql","prisma"],"text":"Title: How to handle conditional prepared statements using prisma and postgresql?\nTags: node.js, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a search query that its parameters changes depending on the client input.\n\n```\nawait prisma.$queryRaw(`SELECT column FROM table ${condition ? `WHERE column = '${condition}'` :' ' } `)\n```\n\nhow can I write this query using prepared statement and avoiding duplicate queries. The only solution I came up with is the following:\n\n```\nconst result = condition ? await prisma.$queryRaw(`SELECT column FROM table WHERE column = $1`,condition) : await prisma.$queryRaw(`SELECT column FROM table`)\n```\n\nThe goal from this is to avoid sql injections from the first query.\n\n**EDIT**\nafter trying the solution suggested by @Ryan I got the following error:\n\n```\nRaw query failed. Code: `22P03`. Message: `db error: ERROR: incorrect binary data format in bind parameter 1`\n```\n\nhere's my implementation:\n\n```\nconst where = Prisma.sql`WHERE ${searchConditions.join(' AND ')}`;\n const fetchCount = await prisma.$queryRaw`\n SELECT \n COUNT(id)\n FROM\n table\n ${searchConditions.length > 0 ? where : Prisma.empty}\n `;\n```\n\nthat will translate to the following in the prisma logs:\n\n```\nQuery: \n SELECT \n COUNT(id)\n FROM\n table\n WHERE $1\n [\"column = something\"]\n```\n\n**SOLUTION**\nI had to do a lot of rework to achieve what I want. Here's the idea behind it:\n\nfor every search condition you need to do the following:\n\n```\nlet queryCondition = Prisma.empty;\n if (searchFilter) {\n const searchFilterCondition = Prisma.sql`column = ${searchFilter}`;\n\n queryCondition.sql.length > 0\n ? (queryCondition = Prisma.sql`${queryCondition} AND ${streamingUnitCondition}`)\n : (queryCondition = searchFilterCondition);\n }\n```\n\nafterwards in the final search query you can do something of this sort:\n\n```\nSELECT COUNT(*) FROM table ${queryCondition.sql.length > 0 ? Prisma.sql`WHERE ${queryCondition}` : Prisma.empty}\n```\n\n========================================\n\nTop Answer:\nHere is my working version, using `Prima.join` :\n\n```\nimport { Prisma } from '@prisma/client'\n\nconst searchConditions: Prisma.Sql[] = []\nif (q) {\n searchConditions.push(Prisma.sql`column = ${q}`)\n}\nconst where = searchConditions.length ? \n Prisma.sql`where ${Prisma.join(searchConditions, ' and ')}` : \n Prisma.empty\n\nawait prisma.$queryRaw(\n Prisma.sql`\n select *\n from table\n ${where}\n `\n)\n```\n\n========================================\n\nCode:\n```text\nawait prisma.$queryRaw(`SELECT column FROM table ${condition ? `WHERE column = '${condition}'`  :' ' } `)\n```\n\n```text\nconst result = condition ? await prisma.$queryRaw(`SELECT column FROM table WHERE column = $1`,condition) : await prisma.$queryRaw(`SELECT column FROM table`)\n```\n\n```text\nRaw query failed. Code: `22P03`. Message: `db error: ERROR: incorrect binary data format in bind parameter 1`\n```\n\n```text\nconst where = Prisma.sql`WHERE ${searchConditions.join(' AND ')}`;\n    const fetchCount = await prisma.$queryRaw`\n    SELECT \n      COUNT(id)\n    FROM\n      table\n    ${searchConditions.length > 0 ? where : Prisma.empty}\n  `;\n```\n\n```text\nQuery: \n    SELECT \n      COUNT(id)\n    FROM\n      table\n    WHERE $1\n   [\"column = something\"]\n```\n\n```text\nlet queryCondition = Prisma.empty;\n    if (searchFilter) {\n      const searchFilterCondition = Prisma.sql`column = ${searchFilter}`;\n\n      queryCondition.sql.length > 0\n        ? (queryCondition = Prisma.sql`${queryCondition} AND ${streamingUnitCondition}`)\n        : (queryCondition = searchFilterCondition);\n    }\n```\n\n```text\nSELECT COUNT(*) FROM table ${queryCondition.sql.length > 0 ? Prisma.sql`WHERE ${queryCondition}` : Prisma.empty}\n```\n\n```text\nimport { Prisma } from '@prisma/client'\n\nconst where = Prisma.sql`where column = ${condition}`\n\nconst result = await prisma.$queryRaw`SELECT column FROM table ${condition ? where : Prisma.empty}`\n```\n\n```text\nimport { Prisma } from '@prisma/client'\n\nconst searchConditions: Prisma.Sql[] = []\nif (q) {\n  searchConditions.push(Prisma.sql`column = ${q}`)\n}\nconst where = searchConditions.length ? \n  Prisma.sql`where ${Prisma.join(searchConditions, ' and ')}` : \n  Prisma.empty\n\nawait prisma.$queryRaw(\n  Prisma.sql`\n    select *\n    from table\n    ${where}\n    `\n)\n```\n\n```text\nPrima.join\n```\n\n========================================\n\nComments:\n- thanks for you input. This worked when no condtions are passed, but once at least one parameter is given, an error is thrown. I updated my question with your suggestion. Can you take a look at it? thanks\n- In that case, you need to do something like this.\n- Your first suggestion led me to the right response. I also followed the documentation prisma.io/docs/concepts/components/prisma-client/&hellip; so I'm gonna mark your response as the correct one.","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":187,"estimatedTokens":1192}}108{"id":"stack-75515214","source":"stackoverflow","questionId":75515214,"title":"Why can't 'npx prisma db push' find my prisma schema?","tags":["database","database-schema","prisma","planetscale","t3"],"text":"Title: Why can't 'npx prisma db push' find my prisma schema?\nTags: database, database-schema, prisma, planetscale, t3\nSource: Stack Overflow\n\nQuestion:\nI'm trying to setup my first t3 app and I have no idea how prisma works. Trying to set up my database following a tutorial and **I cannot get my prisma schema to push.** I the tutorial *precisely* and it still doesn't work.\n\n**Command:**\n\n```\nnpx prisma db push\n```\n\n**Error:**\n\nError: 'could not find a schema.prisma file that is required for this command'\n\n...but my prisma file exists.\n\n**Code:**\n\nDatabase is created on planetscale. Directory setup using create-t3-app.\n\nschema.prisma\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = ['referentialIntegrity']\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n referentialIntegrity = \"prisma\"\n}\n\nmodel Example {\n id String @id @default(cuid())\n name String\n checked Boolean\n}\n```\n\n.env\n\n```\n# When adding additional environment variables, the schema in \"/src/env.mjs\"\n# should be updated accordingly.\n\n# Prisma\n# https://www.prisma.io/docs/reference/database-reference/connection-urls#env\nDATABASE_URL=mysql://mekxxh8g4nqmo6262jnc:**********@us-east.connect.psdb.cloud/mikes-first-crappy-db?sslaccept=strict\n```\n\npackage.json:\n\n```\n\"prisma\": {\n \"schema\": \"./prisma/schema.prisma\"\n }\n```\n\n**Solutions I have tried and have not worked:**\n\nThis site recommends updating the json. I have tried this but I still cannot push my schema. I have also tried wrapping my `DATABASE_URL` in double, single, and no quotes. I have installed the `prisma@4.10.1` package. None of these have worked for me. Just not sure what I could be doing wrong.\n\n========================================\n\nTop Answer:\n**npx prisma db push** not working or not responding with next js\n\nTry shutting down the other server of next js and then again run **npx prisma db push**.\nIt worked for me\n\n========================================\n\nCode:\n```bash\nnpx prisma db push\n```\n\n```none\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n    provider = \"prisma-client-js\"\n    previewFeatures = ['referentialIntegrity']\n}\n\ndatasource db {\n    provider = \"mysql\"\n    url      = env(\"DATABASE_URL\")\n    referentialIntegrity = \"prisma\"\n}\n\nmodel Example {\n    id        String   @id @default(cuid())\n    name String\n    checked Boolean\n}\n```\n\n```ini\n# When adding additional environment variables, the schema in \"/src/env.mjs\"\n# should be updated accordingly.\n\n# Prisma\n# https://www.prisma.io/docs/reference/database-reference/connection-urls#env\nDATABASE_URL=mysql://mekxxh8g4nqmo6262jnc:**********@us-east.connect.psdb.cloud/mikes-first-crappy-db?sslaccept=strict\n```\n\n```json\n\"prisma\": {\n    \"schema\": \"./prisma/schema.prisma\"\n  }\n```\n\n```text\nDATABASE_URL\n```\n\n```text\nprisma@4.10.1\n```\n\n```text\nnpx prisma db push --schema='/location/to/schema.prisma'\n```\n\n```text\nnpx prisma db push\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"mysql\"\n  url = env(\"DATABASE_URL\")\n}\n\nmodel Category {\n  id        String    @id @default(cuid())\n  name      String \n  checked   Boolean\n}\n```\n\n```text\nnpx prisma db push\n```\n\n========================================\n\nComments:\n- I was not in the root location, so stupid.\n- Please edit your post to add code and data as text (using code formatting), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and many more reasons. Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data.","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":164,"estimatedTokens":966}}109{"id":"stack-68841406","source":"stackoverflow","questionId":68841406,"title":"Prisma model self-referencing (one to many)","tags":["postgresql","next.js","one-to-many","database-schema","prisma"],"text":"Title: Prisma model self-referencing (one to many)\nTags: postgresql, next.js, one-to-many, database-schema, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to create an schema where an entity `Chapter` has children that are also `Chapter`.\n\nIt has to be a relation one to many since one chapter can have many children but only one parent.\n\nI'm finding it difficult to define it in my Prisma schema. I have tried some approaches but always show an error:\n\n```\n// children and parent fields\nmodel Chapter {\n id Int @default(autoincrement()) @id\n // ...\n children Chapter[] @relation(\"children\")\n parent Chapter? @relation(fields: [parentId], references: [id])\n parentId Int?\n}\n\n// children field whith @relation\nmodel Chapter {\n id Int @default(autoincrement()) @id\n // ...\n children Chapter[] @relation(\"children\")\n}\n\n// just children as an array of Chapter\nmodel Chapter {\n id Int @default(autoincrement()) @id\n // ...\n children Chapter[]\n}\n\n// Only parent (I could work with that)\nmodel Chapter {\n id Int @default(autoincrement()) @id\n // ...\n parent Chapter? @relation(fields: [parentId], references: [id])\n parentId Int?\n}\n```\n\nAny ideas?\n\n========================================\n\nCode:\n```text\n// children and parent fields\nmodel Chapter {\n  id          Int       @default(autoincrement()) @id\n  // ...\n  children    Chapter[] @relation(\"children\")\n  parent      Chapter?  @relation(fields: [parentId], references: [id])\n  parentId    Int?\n}\n\n// children field whith @relation\nmodel Chapter {\n  id          Int       @default(autoincrement()) @id\n  // ...\n  children    Chapter[] @relation(\"children\")\n}\n\n// just children as an array of Chapter\nmodel Chapter {\n  id          Int       @default(autoincrement()) @id\n  // ...\n  children    Chapter[]\n}\n\n// Only parent (I could work with that)\nmodel Chapter {\n  id          Int       @default(autoincrement()) @id\n  // ...\n  parent      Chapter?  @relation(fields: [parentId], references: [id])\n  parentId    Int?\n}\n```\n\n```text\nChapter\n```\n\n```text\nChapter\n```\n\n```text\nmodel Chapter {\n  id       Int       @id @default(autoincrement())\n  children Chapter[] @relation(\"children\")\n  parent   Chapter?  @relation(\"children\", fields: [parentId], references: [id])\n  parentId Int?      @map(\"chapterId\")\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.823Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":98,"estimatedTokens":565}}110{"id":"stack-73196337","source":"stackoverflow","questionId":73196337,"title":"Prisma update query only allowing an update by the ID field and not anything else","tags":["prisma"],"text":"Title: Prisma update query only allowing an update by the ID field and not anything else\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\n```\nconst response = await prisma.teamMember.update({\n where: {\n teamId,\n userId: memberToEditId,\n },\n data: {\n role,\n },\n });\n```\n\n```\nArgument where of type TeamMemberWhereUniqueInput needs exactly one argument, but you provided teamId and userId. Please choose one. Available args:\ntype TeamMemberWhereUniqueInput {\n id?: String\n}\nUnknown arg `teamId` in where.teamId for type TeamMemberWhereUniqueInput. Did you mean `id`? Available args:\ntype TeamMemberWhereUniqueInput {\n id?: String\n}\nUnknown arg `userId` in where.userId for type TeamMemberWhereUniqueInput. Did you mean `id`? Available args:\ntype TeamMemberWhereUniqueInput {\n id?: String\n}\n```\n\nHey guys. I'm trying to update a specific document based off of a specific value(s) in my table, but it only seems to let me use the primary key for the table? My schema looks like:\n\n```\nmodel TeamMember {\n id String @id @default(cuid())\n teamId String\n userId String\n role Role @default(MEMBER)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n\nmodel Team {\n id String @id @default(cuid())\n name String\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n TeamMember TeamMember[]\n}\n\nmodel User {\n id String @id @default(cuid())\n name String?\n email String? @unique\n emailVerified DateTime?\n image String?\n accounts Account[]\n sessions Session[]\n TeamMember TeamMember[]\n theme Theme @default(LIGHT)\n}\n```\n\nTo fix this, temporarliy I can make a separate findFirst query, and use the returned row to get the ID of the row which i want to update. This is fine, however I know it can be done without doing this, and it is a little ugly having two queries when one can work just fine.\n\nAny help would be greatly appreciated.\n\n========================================\n\nTop Answer:\nAs of Prisma v5 (general introduction of `extendedWhereUnique`), you can just update from `@unique` fields:\n\n```\nmodel TeamMember {\n id String @id @default(cuid())\n teamId String \n userId String @unqiue // Reference to `extendedWhereUnique`:\nhttps://www.prisma.io/docs/concepts/components/preview-features/client-preview-features#preview-features-promoted-to-general-availability\n\n========================================\n\nCode:\n```js\nconst response = await prisma.teamMember.update({\n    where: {\n      teamId,\n      userId: memberToEditId,\n    },\n    data: {\n      role,\n    },\n  });\n```\n\n```js\nArgument where of type TeamMemberWhereUniqueInput needs exactly one argument, but you provided teamId and userId. Please choose one. Available args:\ntype TeamMemberWhereUniqueInput {\n  id?: String\n}\nUnknown arg `teamId` in where.teamId for type TeamMemberWhereUniqueInput. Did you mean `id`? Available args:\ntype TeamMemberWhereUniqueInput {\n  id?: String\n}\nUnknown arg `userId` in where.userId for type TeamMemberWhereUniqueInput. Did you mean `id`? Available args:\ntype TeamMemberWhereUniqueInput {\n  id?: String\n}\n```\n\n```text\nmodel TeamMember {\n  id        String   @id @default(cuid())\n  teamId    String\n  userId    String\n  role      Role     @default(MEMBER)\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)\n  user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n\nmodel Team {\n  id         String       @id @default(cuid())\n  name       String\n  createdAt  DateTime     @default(now())\n  updatedAt  DateTime     @updatedAt\n  TeamMember TeamMember[]\n}\n\n\nmodel User {\n  id            String       @id @default(cuid())\n  name          String?\n  email         String?      @unique\n  emailVerified DateTime?\n  image         String?\n  accounts      Account[]\n  sessions      Session[]\n  TeamMember    TeamMember[]\n  theme         Theme        @default(LIGHT)\n}\n```\n\n```text\nwhereUnique\n```\n\n```text\nupdateMany\n```\n\n```text\nmodel TeamMember {\n  id        String   @id @default(cuid())\n  teamId    String   \n  userId    String   @unqiue // <-- Important\n  role      Role     @default(MEMBER)\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)\n  user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n```\n\n```text\nconst response = await prisma.teamMember.update({\n    where: {\n      teamId,\n      userId: memberToEditId, // <-- this operation will now work because it is unique\n    },\n    data: {\n      role,\n    },\n  });\n```\n\n```text\nextendedWhereUnique\n```\n\n```text\n@unique\n```\n\n```text\nextendedWhereUnique\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.824Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":194,"estimatedTokens":1201}}111{"id":"stack-67930989","source":"stackoverflow","questionId":67930989,"title":"prisma Order by relation has only _count property. Can not order by relation fields","tags":["sql","postgresql","prisma","prisma2"],"text":"Title: prisma Order by relation has only _count property. Can not order by relation fields\nTags: sql, postgresql, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nconsider following Prisma schema:\n\n```\nmodel Conversation {\n id Int @id @default(autoincrement())\n createdAt DateTime @db.Timestamp(6)\n messages ConversationMessage[]\n}\n\nmodel ConversationMessage {\n id Int @id @default(autoincrement())\n text String @db.VarChar(1000)\n sentAt DateTime @map(\"sent_at\") @db.Timestamp(6)\n conversationId Int? @map(\"conversation_id\")\n userId Int? @map(\"user_id\")\n conversation Conversation? @relation(fields: [conversationId], references: [id])\n sender User? @relation(fields: [userId], references: [id])\n}\n```\n\nI want to run such query so that I get a list of conversations ordered by date of their messages, i.e. the ones with new messages first.\n\n```\nprisma.conversation.findMany({\n orderBy: {\n messages: {\n sentAt: 'desc'\n }\n },\n ...\n})\n```\n\nBut the only way that I can query now is like this, i.e. relation has only `_count` property somehow.\n\n```\nprisma.conversation.findMany({\n orderBy: {\n messages: {\n '_count': 'desc'\n }\n },\n ...\n})\n```\n\nEnvironment & setup\n\n```\nOS: Mac OS,\n Database: PostgreSQL\n Node.js version: v12.19.0\n```\n\nPrisma Version\n\n```\nprisma : 2.24.1\n@prisma/client : 2.24.1\nCurrent platform : darwin\nQuery Engine : query-engine 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/query-engine-darwin)\nMigration Engine : migration-engine-cli 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/migration-engine-darwin)\nIntrospection Engine : introspection-core 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/introspection-engine-darwin)\nFormat Binary : prisma-fmt 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/prisma-fmt-darwin)\nDefault Engines Hash : 18095475d5ee64536e2f93995e48ad800737a9e4\nStudio : 0.397.0\nPreview Features : orderByRelation\n```\n\nThank You!\n\n========================================\n\nTop Answer:\nWhile Prisma V2.19 introduced sort by relation aggregate value, as of this writing, the only aggregate property supported is `count`. To the best of my knowledge, what you are asking for is not directly supported by Prisma at the moment. It would be possible if they add `min` and `max` aggregate properties for sorting.\n\nA possible workaround is to sort the messages inside Node.js after retrieval. I'm adding a solution that uses the `orderByRelation` preview feature to simplify the sorting and ensure the messages in a conversation are always ordered (newest first).\n\n### Updating Prisma Client to use `orderByRelation` preview feature.\n\nFirst, update `schema.prisma` to add the preview feature\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"orderByRelation\"]\n}\n```\n\nNow update the prisma client\n\n```\nprisma generate client\n```\n\n### Get `conversations` and sort them by most recent message\n\n```\n// Assuming inside an async function \n\nlet unsortedConversations = await prisma.conversation.findMany({\n include: {\n messages: {\n orderBy: { \n sentAt: 'desc' // messages for each converastion will be ordered newest first. \n }\n }\n },\n // other conditions\n})\n```\n\n`unsortedConversations` contains all required conversations, but they are unordered. You can sort it in the desired order by creating a custom comparator function.\n\n```\nfunction conversationComparatorFunction(conversationA, conversationB) {\n // Conversations with 0 messages will be placed last in arbitrary order. \n if (!conversationB.messages.length) return 1; \n if (!conversationA.messages.length) return -1;\n \n // sort conversations based on sentAt date of the first message. \n // since messages were previously sorted, messages[0] always contain the most recent message. \n if (conversationA.messages[0].sentAt > conversationB.messages[0].sentAt) {\n return -1;\n } else if (conversationA.messages[0].sentAt Be warned though, if the number of `Conversation` records is *very* large sorting on the application side could lead to poor performance, especially considering Node.js is single-threaded.\n\n========================================\n\nCode:\n```text\nmodel Conversation {\n  id           Int                         @id @default(autoincrement())\n  createdAt    DateTime                    @db.Timestamp(6)\n  messages     ConversationMessage[]\n}\n\nmodel ConversationMessage {\n  id             Int                     @id @default(autoincrement())\n  text           String                  @db.VarChar(1000)\n  sentAt         DateTime                @map(\"sent_at\") @db.Timestamp(6)\n  conversationId Int?                    @map(\"conversation_id\")\n  userId         Int?                    @map(\"user_id\")\n  conversation   Conversation?           @relation(fields: [conversationId], references: [id])\n  sender         User?                   @relation(fields: [userId], references: [id])\n}\n```\n\n```text\nprisma.conversation.findMany({\n    orderBy: {\n        messages: {\n            sentAt: 'desc'\n        }\n    },\n    ...\n})\n```\n\n```text\nprisma.conversation.findMany({\n    orderBy: {\n        messages: {\n           '_count': 'desc'\n        }\n     },\n     ...\n})\n```\n\n```text\nOS: Mac OS,\n    Database: PostgreSQL\n    Node.js version: v12.19.0\n```\n\n```text\nprisma               : 2.24.1\n@prisma/client       : 2.24.1\nCurrent platform     : darwin\nQuery Engine         : query-engine 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/query-engine-darwin)\nMigration Engine     : migration-engine-cli 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/migration-engine-darwin)\nIntrospection Engine : introspection-core 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/introspection-engine-darwin)\nFormat Binary        : prisma-fmt 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/prisma-fmt-darwin)\nDefault Engines Hash : 18095475d5ee64536e2f93995e48ad800737a9e4\nStudio               : 0.397.0\nPreview Features     : orderByRelation\n```\n\n```text\n_count\n```\n\n```text\nexport async function getConversationsOrderedByMessageSentAt() {\n  return db.$queryRaw`SELECT c.*\n    FROM conversation c\n    JOIN messages m\n        ON c.id = m. conversationId\n    ORDER BY m.sentAt DESC;`;\n}\n```\n\n```text\nrawQuery\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"orderByRelation\"]\n}\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  previewFeatures = [\"orderByRelation\"]\n}\n```\n\n```text\nprisma generate client\n```\n\n```js\n// Assuming inside an async function \n\nlet unsortedConversations = await prisma.conversation.findMany({\n    include: {\n        messages: {\n            orderBy: {    \n                sentAt: 'desc'  // messages for each converastion will be ordered newest first. \n            }\n        }\n    },\n    // other conditions\n})\n```\n\n```js\nfunction conversationComparatorFunction(conversationA, conversationB) {\n    // Conversations with 0 messages will be placed last in arbitrary order. \n    if (!conversationB.messages.length) return 1;  \n    if (!conversationA.messages.length) return -1;\n    \n    // sort conversations based on sentAt date of the first message. \n    // since messages were previously sorted, messages[0] always contain the most recent message. \n    if (conversationA.messages[0].sentAt > conversationB.messages[0].sentAt) {\n        return -1;\n    } else if (conversationA.messages[0].sentAt < conversationB.messages[0].sentAt) {\n        return 1;\n    } else return 0;\n\n}\n\nlet sortedConversations = unsortedConversations.sort(conversationComparatorFunction)\n```\n\n```text\ncount\n```\n\n```text\nmin\n```\n\n```text\nmax\n```\n\n```text\norderByRelation\n```\n\n```text\norderByRelation\n```\n\n```text\nschema.prisma\n```\n\n```text\nconversations\n```\n\n```text\nunsortedConversations\n```\n\n```text\nConversation\n```\n\n```text\norderBy: {\n  lastChildUpdatedAt: \"desc\",\n}\n```\n\n```text\nlastChildUpdatedAt\n```\n\n========================================\n\nComments:\n- Thanks! I resolved this similarly, but added sorting on the client.\n- Sad that this is still not supported :(\n- I guess this is the way to do it in Prisma, but I'd rather like to have just a sort field of a joined table. I wonder why this is not supported.\n- Thanks for idea, it is the best solution for me. In my case it's easy to control events of child creation and this solution also uses db's perfomance (not sorting manually on backend part).","metadata":{"transformedAt":"2026-08-18T18:33:14.824Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":316,"estimatedTokens":2117}}112{"id":"stack-74013936","source":"stackoverflow","questionId":74013936,"title":"Prisma - The provided database string is invalid. MongoDB connection string error","tags":["javascript","mongodb","next.js","prisma"],"text":"Title: Prisma - The provided database string is invalid. MongoDB connection string error\nTags: javascript, mongodb, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm being told I have an invalid connection string for my MongoDB data provider.\n\nSpecifically, I'm getting this: `The provided database string is invalid. MongoDB connection string error: Missing delimiting slash between hosts and options in database URL.`\n\nMy problem, however, is that my connection string **does** have a delimiting slash: it's this: `mongodb://:@cluster0..mongodb.net/?retryWrites=true&w=majority`\n\nWhat's going on? Is there anything I'm missing?\n\n========================================\n\nTop Answer:\nFor someone who tried to connect mongodb in prisma, maybe you choose wrong connect , try to use type connect using VSCode\n\n```\nmongodb+srv://:@cluster0.8hjts4c.mongodb.net/test\n```\n\nit must have `/test`\n\n========================================\n\nCode:\n```text\nThe provided database string is invalid. MongoDB connection string error: Missing delimiting slash between hosts and options in database URL.\n```\n\n```text\nmongodb://<user>:<pass>@cluster0.<server>.mongodb.net/?retryWrites=true&w=majority\n```\n\n```text\nmongodb://<user>:<pass>@cluster0.<server>.mongodb.net/<mydb>?retryWrites=true&w=majority\n```\n\n```text\nmongodb://<user>:<pass>@cluster0.<server>.mongodb.net/<name>?retryWrites=true&w=majority\n```\n\n```text\n<name>\n```\n\n```text\nmongodb+srv://<admin>:<password>@cluster0.8hjts4c.mongodb.net/test\n```\n\n```text\n/test\n```\n\n```text\nDATABASE_URL=\"mongodb+srv://<user>:<pass>@<cluster_name>/<colection_name>? \n retryWrites=true&w=majority\"\n```\n\n```text\nDATABASE_URL=\"mongodb+srv://<user>:<pass>@<cluster_name>/<colection_name>? \n retryWrites=true&w=majority\"\n```\n\n```text\nDATABASE_URL=\"mongodb+srv://sammy:devland@<cluster_name>/<colection_name>? \n retryWrites=true&w=majority\"\n```\n\n========================================\n\nComments:\n- Thanks! its interesting that the url provided by Atlas (the mother of mongodb) is not including that /dbname at the end.","metadata":{"transformedAt":"2026-08-18T18:33:14.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":74,"estimatedTokens":512}}113{"id":"stack-71408235","source":"stackoverflow","questionId":71408235,"title":"How is .upsertMany() implemented in Prisma ORM?","tags":["javascript","node.js","typescript","orm","prisma"],"text":"Title: How is .upsertMany() implemented in Prisma ORM?\nTags: javascript, node.js, typescript, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nPrisma ORM has an implementation of the update or create `upsert()` method and a group of\nbulk requests,\n\nbut there is no such thing as `.upsertMany()`, i.e. bulk \"create or update existing records\".\n\nWhat is the best way to implement such a method using Prisma ORM?\n\n========================================\n\nTop Answer:\nYou can use upsert to update multiple objects like the following:\nIn the following example, I am updating a user's profile and upserting multiple addresses by using the map function.\n\n```\nawait this.prisma.user.update({\n where: {\n id: user.id\n },\n data:{\n fullName: saveUserProfileDto?.fullName,\n email: saveUserProfileDto?.email,\n \n userAddresses: {\n upsert: saveUserProfileDto?.addresses?.map(address => ({\n where: {\n uuid: address.uuid || \"\"\n },\n create: {\n uuid: uuidv4(),\n country: address.country,\n cityTown: address.cityTown,\n streetAddress: address.streetAddress,\n apartmentSuit: address.apartmentSuit,\n },\n update: {\n country: address.country,\n cityTown: address.cityTown,\n streetAddress: address.streetAddress,\n apartmentSuit: address.apartmentSuit,\n }\n }))\n }\n }\n });\n```\n\n**So you don't need to delete anything before upserting.**\n\n========================================\n\nCode:\n```text\nupsert()\n```\n\n```text\n.upsertMany()\n```\n\n```js\nconst collection = await prisma.$transaction(\n    userData.map(cur =>\n      prisma.cur.upsert({\n        where: { id: cur.id },\n        update: {},\n        create: { id: cur.id },\n      })\n    )\n  )\n```\n\n```text\nupsertMany\n```\n\n```text\nupsertMany\n```\n\n```text\nupsert\n```\n\n```text\n$transaction\n```\n\n```text\n$transaction\n```\n\n```text\ncreateMany\n```\n\n```text\nupdateMany\n```\n\n```text\nawait this.prisma.user.update({\n                where: {\n                    id: user.id\n                },\n                data:{\n                    fullName: saveUserProfileDto?.fullName,\n                    email: saveUserProfileDto?.email,\n                    \n                    userAddresses: {\n                        upsert: saveUserProfileDto?.addresses?.map(address => ({\n                            where: {\n                                uuid: address.uuid || \"\"\n                            },\n                            create: {\n                                uuid: uuidv4(),\n                                country: address.country,\n                                cityTown: address.cityTown,\n                                streetAddress: address.streetAddress,\n                                apartmentSuit: address.apartmentSuit,\n                            },\n                            update: {\n                                country: address.country,\n                                cityTown: address.cityTown,\n                                streetAddress: address.streetAddress,\n                                apartmentSuit: address.apartmentSuit,\n                            }\n                        }))\n                    }\n                }\n            });\n```\n\n========================================\n\nComments:\n- you can see my answer here about prisma extends: stackoverflow.com/a/79657035/14473507\n- Maybe I'm missing some techniological barrier for why there isn't a better way of doing this? But if I want to upsert 10 million records of demo data, using their own seeding system, I'd have to actually fire 10 million separate queries against the db?\n- If you do this, make sure you have a plan for stale reads for concurrent connections. I believe this can lead to a situation where (1) You do your read, (2) Another user issues a create, (3) You issue your create and get an error from Prisma. Won't happen if you're just working with test data, but at high scale and/or high data overlap will probably give you issues.\n- Smart! Does this execute in a single database query?\n- No. The upsert operation for user addresses takes multiple queries to execute.\n- So each address is upserted in a separate round-trip to the DB?\n- Yes, each address in the `saveUserProfileDto.addresses` array is upserted in a separate round-trip to the database.","metadata":{"transformedAt":"2026-08-18T18:33:14.827Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":147,"estimatedTokens":1044}}114{"id":"stack-75746794","source":"stackoverflow","questionId":75746794,"title":"How to add an empty migration in prisma?","tags":["sql","database","migration","relational-database","prisma"],"text":"Title: How to add an empty migration in prisma?\nTags: sql, database, migration, relational-database, prisma\nSource: Stack Overflow\n\nQuestion:\nI need to add an empty migration to write a SQL query and manipulate the data manually.\n\nThere is no change in my schema and basically, I just need to apply this query to my existing data.\n\n========================================\n\nCode:\n```text\nprisma migrate dev --create-only --name <NAME_OF_YOUR_MIGRATION>\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.827Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":15,"estimatedTokens":114}}115{"id":"stack-51611400","source":"stackoverflow","questionId":51611400,"title":"Prisma: What's the workflow?","tags":["graphql","prisma","prisma-graphql"],"text":"Title: Prisma: What's the workflow?\nTags: graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nJust started using Prisma as a way to integrate GraphQL and MySQL into a new project I am working on. It's great, I love how simply it lays things out. I have a few questions which are bothering me though regarding the workflow to when developing with Prisma. \n\nFor example:\n\nYesterday I setup the basic Prisma and GraphQL server as per the tutorial. It all worked well. I only have a single type modelled in my datamodel.graphql. \n\nThis morning I wake up and start work on another type and add that to my datamodel.graphql. Docker is running, I update the index.js with resolvers to support the new Model and it's Querys/Mutations. However, when it comes to running the system using `node ./index.js` I get an error saying it isn't aware of the new Model. I suspect the Prisma schema hasn't been refreshed/updated so i run `graphql get-schema --project prisma` but it tells me that nothing has changed. \n\nObviously I'm missing something. I am not working with Prisma in a way it would like. Can anyone illuminate me as to the order of events which have to take place for things to run smoothly?\n\nThe tutorial is great for getting you up and running but I feel like it doesn't well introduce developers into the flow of using Prisma on a day-to-day continuous development cycle. \n\nAny info/insight/links would be very useful. \n\nMany thanks,\n\nA\n\n**UPDATE**\n\nFor anyone else who has become a little lost about the workflow. Take a look at the CLI reference. It's very useful for all Prisma related tasks (not necessarily all things to do with your GraphQL server). LINK\n\n**TL;DR:** \n\nYou need to redeploy your prisma service each time the datamodel changes so that the generated prisma.graphql can be updated with new functionality to work with the DB. I ran `prisma deploy` and voila!\n\n========================================\n\nTop Answer:\nDon't forget to deploy your datamodel with `prisma deploy`.\n\nYou have a full working example here: \nhttps://github.com/alan345/naperg\n\n========================================\n\nCode:\n```text\nnode ./index.js\n```\n\n```text\ngraphql get-schema --project prisma\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma deploy\n```\n\n```text\n// prisma.yml file\n\ndatamodel: datamodel.prisma\ngenerate:\n  - generator: javascript-client\n    output: ../src/generated/prisma-client\n\nhooks:\n  post-deploy:\n    - prisma generate\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma generate\n```\n\n```text\nprisma.yml\n```\n\n```text\nprisma generate\n```\n\n```text\nprisma deploy\n```\n\n========================================\n\nComments:\n- What tutorial did you use to get started with Prisma?\n- To make it more accurate, `prisma deploy` is to apply your changes and migrate the underlying database schema. But you also have to do `prisma generate` to update the auto-generated Prisma client so that it can expose CRUD methods for any newly added model.","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":100,"estimatedTokens":746}}116{"id":"stack-72195741","source":"stackoverflow","questionId":72195741,"title":"Use of @map and @@map for Prisma schema","tags":["prisma"],"text":"Title: Use of @map and @@map for Prisma schema\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI am new to Prisma and have been wondering what is the use of @map and @@map for Prisma schema? I have looked at their website: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#map but still don't fully get the purpose of @map and @@map.\n\nFrom what I can comprehend, if I have something like\nlastName String @map(\"last_name\") @db.VarChar(256)\nit maps \"last_name\" to lastname? But I am not too sure when I will need this.\n\nThank you! Appreciate any help.\n\n========================================\n\nTop Answer:\nMaps a field name or enum value from the Prisma schema to a column or document field with a different name in the database\n\nA use case could be people integrating existing database with prisma and want to use different naming conventions between database & prisma client.\n\nFor example, one might use snakecase for database column but want to use camelcase for prisma client, then they will do:\n\n```\nmodel User {\n createdAt String @map(\"created_at\")\n}\n```\n\nSame thing with @@map, but just for table name.\n\nDetailed guide from prisma:\n\nhttps://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/use-custom-model-and-field-names\n\n========================================\n\nCode:\n```text\nmodel User {\n  id        Int    @id @default(autoincrement())\n  userLastName String @map(\"user_last_name\")\n}\n```\n\n```text\nmodel UserDetails {\n  id   Int    @id @default(autoincrement())\n  name String\n\n  @@map(\"users_details\")\n}\n```\n\n```text\n@map\n```\n\n```text\nuserLastName\n```\n\n```text\nuser_last_name\n```\n\n```text\nPrismaClient\n```\n\n```text\n@map\n```\n\n```text\n@map\n```\n\n```text\n@map\n```\n\n```text\n@@map\n```\n\n```text\nUserDetails\n```\n\n```text\nuser_details\n```\n\n```text\n@@map\n```\n\n```text\n@map\n```\n\n```text\nmodel User {\n  createdAt String @map(\"created_at\")\n}\n```\n\n========================================\n\nComments:\n- Is this answer outdated or am I reading it wrong? What this says about where the name in `@map` is used has it the wrong way around. `@map` and `@@map` changes the names used in the database columns and tables, *not* in the Prisma client. This answer seems to say the opposite.\n- It's more like \"the other way around\" but also it's sort of both and neither. I think the answer could be made clearer or more explicit : With `@map` and `@@map` the string provided as argument is the name to use in database for the column or model, while the original column or model name is what is used in the generated prisma client.","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":112,"estimatedTokens":643}}117{"id":"stack-55000909","source":"stackoverflow","questionId":55000909,"title":"Auto generated Incrementing field for prisma","tags":["prisma","prisma-graphql"],"text":"Title: Auto generated Incrementing field for prisma\nTags: prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI have created an entity called `Order` in my `datamodel.prisma` file. there it should have it's automatically generating field called `orderRef`. which should have an automatically generated incremental value for `createOrder` field of the Order entity for each mutation call.\n\nfor the first Order the value of the 'orderRef' field should be OD1, the second Order should have the value OD2 for the field 'orderRef' and so on.\neg: \n\n(OD1, OD2, ....... OD124, ..... )\n\nWhat is the easiest way to achieve this?\nyes **the value should be String, instead of Number.**\n\n========================================\n\nCode:\n```text\nOrder\n```\n\n```text\ndatamodel.prisma\n```\n\n```text\norderRef\n```\n\n```text\ncreateOrder\n```\n\n```text\nquery {\n  things(orderBy: createdAt_desc, first: 1) {\n    myId\n  }\n}\n\n...\nnewId = myId + 1\n...\n\nmutation {\n  createThing(data: {myId: newId, ... }) {\n    ...\n  }\n}\n```\n\n```text\nquery {\n  thingsConnection {\n    aggregate {\n      count\n    }\n  }\n}\n...\nnewId = count + 1\n...\n\nmutation {\n  createThing(data: {myId: newId, ... }) {\n    ...\n  }\n}\n```\n\n========================================\n\nComments:\n- Thank you.! I also spent a considerable amount of time searching for an answer on this issue. I believe in your first solution as the best solution that is currently available. Since the client can delete existing orders I can't use the second solution although it seems the easiest one to implement. and our system will have considerable amount of orders. 6 letter random string might not suit. I decided to continue with your first answer.","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":419}}118{"id":"stack-68174649","source":"stackoverflow","questionId":68174649,"title":"How to change PrismaClient database connection at runtime?","tags":["javascript","prisma"],"text":"Title: How to change PrismaClient database connection at runtime?\nTags: javascript, prisma\nSource: Stack Overflow\n\nQuestion:\nI have .env file like\n\n```\nDATABASE_URL=\"sqlserver://srv:50119;initial catalog=mydb;user=aaa;password=bbb;\"\n```\n\nand then schema.prisma like\n\n```\ndatasource db {\n provider = \"sqlserver\"\n url = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"microsoftSqlServer\"]\n}\n```\n\nI generate a client using:\n\n```\nnpx prisma generate\n```\n\nand then Prisma works great in my express app using:\n\n```\nconst prisma = new PrismaClient();\n```\n\nSay I wanted to use a different db for user for multi-tenancy, how can I achieve this? Ideally I'd want to switch the db connection at runtime but it seems that DATABASE_URL is only read during prisma generate and not at runtime so the generated client ends up with a hardcoded db url.\n\n========================================\n\nCode:\n```text\nDATABASE_URL=\"sqlserver://srv:50119;initial catalog=mydb;user=aaa;password=bbb;\"\n```\n\n```text\ndatasource db {\n  provider = \"sqlserver\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n  previewFeatures = [\"microsoftSqlServer\"]\n}\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nconst prisma = new PrismaClient();\n```\n\n```text\nPrismaClient\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":69,"estimatedTokens":329}}119{"id":"stack-79269631","source":"stackoverflow","questionId":79269631,"title":"Prisma openssl version issue","tags":["docker","docker-compose","openssl","prisma"],"text":"Title: Prisma openssl version issue\nTags: docker, docker-compose, openssl, prisma\nSource: Stack Overflow\n\nQuestion:\nI’m encountering an issue while trying to compose Docker instances in my local environment. When I run the docker-compose up command, I get the following error:\n\n```\n> 2024-12-10 12:46:12 > laredo-backend-api@0.0.1 start:docker:dev\n> 2024-12-10 12:46:12 > npm install && npm run start:prisma && npm run\n> start:dev 2024-12-10 12:46:12 2024-12-10 12:46:16 2024-12-10\n> 12:46:16 added 1 package, and audited 1011 packages in 3s 2024-12-10\n> 12:46:16 2024-12-10 12:46:16 134 packages are looking for funding\n> 2024-12-10 12:46:16 run `npm fund` for details 2024-12-10 12:46:16 \n> 2024-12-10 12:46:16 6 vulnerabilities (1 low, 2 moderate, 3 high)\n> 2024-12-10 12:46:16 2024-12-10 12:46:16 To address issues that do not\n> require attention, run: 2024-12-10 12:46:16 npm audit fix 2024-12-10\n> 12:46:16 2024-12-10 12:46:16 To address all issues, run: 2024-12-10\n> 12:46:16 npm audit fix --force 2024-12-10 12:46:16 2024-12-10\n> 12:46:16 Run `npm audit` for details. 2024-12-10 12:46:16 2024-12-10\n> 12:46:16 > laredo-backend-api@0.0.1 start:prisma 2024-12-10 12:46:16 >\n> prisma migrate deploy 2024-12-10 12:46:16 2024-12-10 12:46:22\n> Environment variables loaded from .env 2024-12-10 12:46:22 Prisma\n> schema loaded from prisma/schema.prisma 2024-12-10 12:46:22 Datasource\n> \"db\": PostgreSQL database \"laredo\", schema \"public\" at \"postgres:5432\"\n> 2024-12-10 12:46:22 2024-12-10 12:46:17 prisma:warn Prisma failed to\n> detect the libssl/openssl version to use, and may not work as\n> expected. Defaulting to \"openssl-1.1.x\". 2024-12-10 12:46:17 Please\n> manually install OpenSSL and try installing Prisma again. 2024-12-10\n> 12:46:22 prisma:warn Prisma failed to detect the libssl/openssl\n> version to use, and may not work as expected. Defaulting to\n> \"openssl-1.1.x\". 2024-12-10 12:46:22 Please manually install OpenSSL\n> and try installing Prisma again. 2024-12-10 12:46:22 Error: Could not\n> parse schema engine response: SyntaxError: Unexpected token 'E',\n> \"Error load\"... is not valid JSON 2024-12-10 12:46:22 npm notice\n> 2024-12-10 12:46:22 npm notice New minor version of npm available!\n> 10.8.2 -> 10.9.2 2024-12-10 12:46:22 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.9.2 2024-12-10 12:46:22\n> npm notice To update run: npm install -g npm@10.9.2 2024-12-10\n> 12:46:22 npm notice\n```\n\nI've done some googling and ran the following commands in order to fix this:\n\n`brew install openssl@3`\n\n`rm -rf node_modules && npm i`\n\n`npx prisma generate`\n\n`npx prisma migrate --dev`\n\nThe follwoing is my prisma generator\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n binaryTargets = [\"native\", \"linux-musl\", \"darwin-arm64\", \"linux-musl-openssl-3.0.x\"]\n}\n```\n\nDocker file\n\n```\nFROM node:20-alpine AS builder\n\nUSER root\n\nRUN npm i -g npm@~9.3.1\n\nWORKDIR /usr/app\n\nCOPY . ./\n\nRUN chmod +x ./entrypoint.sh\n\nRUN npm ci\n\nRUN npm run build\n\nFROM node:20-alpine AS deployment\n\n# added this to try to fix but still broken\n\nRUN set -ex; \\\n apk update; \\\n apk add --no-cache \\\n openssl\n\nCOPY --from=builder --chown=node:node /usr/app /usr/app\n\nUSER node\n\nCMD [\"sh\"]\n```\n\nAny pointers are appreciated thanks!\n\n========================================\n\nTop Answer:\nAdd this to your DockerFile, this works for me!\n\n```\nFROM node:18-alpine\n\nRUN apk add --no-cache openssl\n```\n\n========================================\n\nCode:\n```text\n> 2024-12-10 12:46:12 > laredo-backend-api@0.0.1 start:docker:dev\n> 2024-12-10 12:46:12 > npm install && npm run start:prisma && npm run\n> start:dev 2024-12-10 12:46:12  2024-12-10 12:46:16  2024-12-10\n> 12:46:16 added 1 package, and audited 1011 packages in 3s 2024-12-10\n> 12:46:16  2024-12-10 12:46:16 134 packages are looking for funding\n> 2024-12-10 12:46:16   run `npm fund` for details 2024-12-10 12:46:16 \n> 2024-12-10 12:46:16 6 vulnerabilities (1 low, 2 moderate, 3 high)\n> 2024-12-10 12:46:16  2024-12-10 12:46:16 To address issues that do not\n> require attention, run: 2024-12-10 12:46:16   npm audit fix 2024-12-10\n> 12:46:16  2024-12-10 12:46:16 To address all issues, run: 2024-12-10\n> 12:46:16   npm audit fix --force 2024-12-10 12:46:16  2024-12-10\n> 12:46:16 Run `npm audit` for details. 2024-12-10 12:46:16  2024-12-10\n> 12:46:16 > laredo-backend-api@0.0.1 start:prisma 2024-12-10 12:46:16 >\n> prisma migrate deploy 2024-12-10 12:46:16  2024-12-10 12:46:22\n> Environment variables loaded from .env 2024-12-10 12:46:22 Prisma\n> schema loaded from prisma/schema.prisma 2024-12-10 12:46:22 Datasource\n> \"db\": PostgreSQL database \"laredo\", schema \"public\" at \"postgres:5432\"\n> 2024-12-10 12:46:22  2024-12-10 12:46:17 prisma:warn Prisma failed to\n> detect the libssl/openssl version to use, and may not work as\n> expected. Defaulting to \"openssl-1.1.x\". 2024-12-10 12:46:17 Please\n> manually install OpenSSL and try installing Prisma again. 2024-12-10\n> 12:46:22 prisma:warn Prisma failed to detect the libssl/openssl\n> version to use, and may not work as expected. Defaulting to\n> \"openssl-1.1.x\". 2024-12-10 12:46:22 Please manually install OpenSSL\n> and try installing Prisma again. 2024-12-10 12:46:22 Error: Could not\n> parse schema engine response: SyntaxError: Unexpected token 'E',\n> \"Error load\"... is not valid JSON 2024-12-10 12:46:22 npm notice\n> 2024-12-10 12:46:22 npm notice New minor version of npm available!\n> 10.8.2 -> 10.9.2 2024-12-10 12:46:22 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.9.2 2024-12-10 12:46:22\n> npm notice To update run: npm install -g npm@10.9.2 2024-12-10\n> 12:46:22 npm notice\n```\n\n```text\ngenerator client {\n  provider      = \"prisma-client-js\"\n  binaryTargets = [\"native\", \"linux-musl\", \"darwin-arm64\", \"linux-musl-openssl-3.0.x\"]\n}\n```\n\n```text\nFROM node:20-alpine AS builder\n\nUSER root\n\nRUN npm i -g npm@~9.3.1\n\nWORKDIR /usr/app\n\nCOPY . ./\n\nRUN chmod +x ./entrypoint.sh\n\nRUN npm ci\n\nRUN npm run build\n\nFROM node:20-alpine AS deployment\n\n# added this to try to fix but still broken\n\nRUN set -ex; \\\n    apk update; \\\n    apk add --no-cache \\\n    openssl\n\nCOPY --from=builder --chown=node:node /usr/app /usr/app\n\nUSER node\n\nCMD [\"sh\"]\n```\n\n```text\nbrew install openssl@3\n```\n\n```text\nrm -rf node_modules && npm i\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpx prisma migrate --dev\n```\n\n```text\nFROM node:20-alpine3.17\n```\n\n```text\nFROM node:18-alpine\n\nRUN apk add --no-cache openssl\n```\n\n```js\nFROM node:20-slim\n\nRUN apt-get update -y && apt-get install -y openssl\n```\n\n```text\nopenssl\n```\n\n```text\nDockerfile\n```\n\n```text\nslim\n```\n\n```text\nFROM node:20-alpine\n\nRUN apk update && apk add --no-cache openssl\n```\n\n```text\nFROM node:22.11.0-alpine\n```\n\n```text\n22.11.0\n```\n\n```text\n# Install openssl\nRUN apt-get update\nRUN apt-get install -y openssl\n```\n\n```text\nnode:20-alpine\n```\n\n```text\nnode:18-slim\n```\n\n========================================\n\nComments:\n- Hey , I have the same problem . everything was ok in my project, but suddenly I saw this error and my backend has stoped working\n- @MoeinMoeinnia if you figure it out please let me know\n- I added this to my docker file and ran `docker compose up --build` yet I got the same error\n- was there any other commands you ran to get this to work once making those changes?\n- I just removed all images and cache from pnpm and rebuilt the containers.\n- Try reading this issue: github.com/nodejs/docker-node/issues/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":266,"estimatedTokens":1855}}120{"id":"stack-54501500","source":"stackoverflow","questionId":54501500,"title":"How to delete a record with all relevant records in prisma","tags":["prisma"],"text":"Title: How to delete a record with all relevant records in prisma\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI know that there are some sections related to my question in the documentation of prisma-client:\n\n- deleting objects\n\n- updating and deleting many records\n\nHowever, I can't understand that how can I delete a record with all its related records in (JavaScript) prisma-client.\n\nFor example, my datamodel is something like this:\n\n```\ntype Board {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n owner: User! @relation(name: \"BoardOwnershipRelation\")\n title: String!\n description: String\n taskGroups: [TaskGroup!]!\n}\n\ntype TaskGroup {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n owner: User! @relation(name: \"TaskGroupOwnershipRelation\")\n board: Board!\n title: String!\n description: String\n precedence: Int\n tasks: [Task!]!\n}\n\ntype Task {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n owner: User! @relation(name: \"TaskOwnershipRelation\")\n taskGroup: TaskGroup!\n title: String!\n description: String\n dueDate: DateTime\n precedence: Int\n items: [TaskItem!]!\n assignedTo: [User!]! @relation(name: \"AssignmentRelation\")\n}\n\ntype TaskItem {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n owner: User! @relation(name: \"TaskItemOwnershipRelation\")\n task: Task!\n title: String!\n description: String\n checked: Boolean!\n precedence: Int\n}\n```\n\n***How*** can I delete a Board with all its related TaskGroups, Tasks, and TaskItems ?!\n\n**Edit**:\n\nI've recently tried this solution, which also works well.\n\n```\n// e.g. this is in my GraphQL resolvers async function...\n\nawait prisma.deleteManyTaskItems({\n task: {\n taskGroup: {\n board: {\n id: boardId\n }\n }\n }\n});\n\nawait prisma.deleteManyTasks({\n taskGroup: {\n board: {\n id: boardId\n }\n }\n});\n\nawait prisma.deleteManyTaskGroups({\n board: {\n id: boardId\n }\n});\n\nreturn await prisma.deleteBoard({ id: boardId });\n```\n\nBut, **is there any better solution for my issue ???**\n\n========================================\n\nCode:\n```text\ntype Board {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"BoardOwnershipRelation\")\n  title: String!\n  description: String\n  taskGroups: [TaskGroup!]!\n}\n\ntype TaskGroup {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"TaskGroupOwnershipRelation\")\n  board: Board!\n  title: String!\n  description: String\n  precedence: Int\n  tasks: [Task!]!\n}\n\ntype Task {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"TaskOwnershipRelation\")\n  taskGroup: TaskGroup!\n  title: String!\n  description: String\n  dueDate: DateTime\n  precedence: Int\n  items: [TaskItem!]!\n  assignedTo: [User!]! @relation(name: \"AssignmentRelation\")\n}\n\ntype TaskItem {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"TaskItemOwnershipRelation\")\n  task: Task!\n  title: String!\n  description: String\n  checked: Boolean!\n  precedence: Int\n}\n```\n\n```text\n// e.g. this is in my GraphQL resolvers async function...\n\nawait prisma.deleteManyTaskItems({\n  task: {\n    taskGroup: {\n      board: {\n        id: boardId\n      }\n    }\n  }\n});\n\nawait prisma.deleteManyTasks({\n  taskGroup: {\n    board: {\n      id: boardId\n    }\n  }\n});\n\nawait prisma.deleteManyTaskGroups({\n  board: {\n    id: boardId\n  }\n});\n\nreturn await prisma.deleteBoard({ id: boardId });\n```\n\n```text\ntype Board {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"BoardOwnershipRelation\")\n  title: String!\n  description: String\n  taskGroups: [TaskGroup!]! @relation(name: \"BoardTaskGroups\" onDelete: CASCADE)\n}\n\ntype TaskGroup {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"TaskGroupOwnershipRelation\")\n  board: Board! @relation(name: \"BoardTaskGroups\")\n  title: String!\n  description: String\n  precedence: Int\n  tasks: [Task!]! @relation(name: \"TaskGroupsTask\" onDelete: CASCADE)\n}\n\ntype Task {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"TaskOwnershipRelation\")\n  taskGroup: TaskGroup! @relation(name: \"TaskGroupsTask\")\n  title: String!\n  description: String\n  dueDate: DateTime\n  precedence: Int\n  items: [TaskItem!]! @relation(name: \"TaskTaskItem\" onDelete: CASCADE)\n  assignedTo: [User!]! @relation(name: \"AssignmentRelation\")\n}\n\ntype TaskItem {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  owner: User! @relation(name: \"TaskItemOwnershipRelation\")\n  task: Task! @relation(name: \"TaskTaskItem\")\n  title: String!\n  description: String\n  checked: Boolean!\n  precedence: Int\n}\n```\n\n```text\nonDelete\n```\n\n```text\n@relation\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":243,"estimatedTokens":1186}}121{"id":"stack-68700352","source":"stackoverflow","questionId":68700352,"title":"The underlying table for model 'Order' does not exist. Error code: P1014 (Prisma)","tags":["nestjs","prisma","prisma2"],"text":"Title: The underlying table for model 'Order' does not exist. Error code: P1014 (Prisma)\nTags: nestjs, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have such problem as below\n\n```\n$ prisma migrate dev --name \"ok\"\n \nError: P3006\n \nMigration `2021080415559_order_linking` failed to apply clearnly to the shadow database.\nError code: P1014\nError:\nThe underlying table for model 'Order' does not exist.\n```\n\n**How to fix it?**\n\n========================================\n\nTop Answer:\nIt looks like your migrations were corrupted somehow. There was probably changes to your database that was not recorded in the migration history.\n\nYou could try one of these:\n\n- If you're okay with losing the data in the database, try resetting the database with `prisma migrate reset`. More info\n\n- Try running introspection to capture any changes to the database with `prisma introspect` before applying a new migration. More info\n\n========================================\n\nCode:\n```text\n$ prisma migrate dev --name \"ok\"\n    \nError: P3006\n    \nMigration `2021080415559_order_linking` failed to apply clearnly to the shadow database.\nError code: P1014\nError:\nThe underlying table for model 'Order' does not exist.\n```\n\n```text\n*delete the migrations folder*\n\n$ prisma generate\n\n$ prisma migrate dev --name \"ok\"\n\n*it works*\n```\n\n```text\nprisma migrate reset\n```\n\n```text\nprisma introspect\n```\n\n========================================\n\nComments:\n- be aware, deleting all migration files could negatively impact on your further development","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":67,"estimatedTokens":381}}122{"id":"stack-53373101","source":"stackoverflow","questionId":53373101,"title":"Prisma Datamodel: Primary key as a combination of two relational models","tags":["mysql","graphql","prisma"],"text":"Title: Prisma Datamodel: Primary key as a combination of two relational models\nTags: mysql, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a problem in Prisma data modeling where I have **to constrain that a user can submit only one review for a product**. I have **following design for the non-constrained situation**.\n\n Should `Customer` and `Product` be combined into a primary key in `ProductReview` model, or should this constraint be imposed at the application server level, and not at the database level?\n\nDatamodel for now (non-constrained version):\n\n```\ntype Product {\n id: ID! @unique\n title: String!\n reviews: [ProductReview!]! @relation(name: \"ProductReviews\", onDelete: CASCADE)\n}\n\ntype Customer {\n id: ID! @unique\n email: String @unique\n}\n\ntype ProductReview {\n id: ID! @unique\n forProduct: Product! @relation(name: \"ProductReviews\", onDelete: SET_NULL)\n byCustomer: Customer!\n review: String!\n ratinng: Float!\n}\n```\n\n========================================\n\nTop Answer:\nPrisma v2 introduced composite primary keys:\n\nhttps://newreleases.io/project/github/prisma/prisma/release/2.0.0-preview023\n\nAn example from that link:\n\n```\nmodel User {\n firstName String\n lastName String\n email String\n\n @@id([firstName, lastName])\n}\n```\n\nSo in the given question example, it is now possible to add to `ProductReview`:\n\n```\n@@id([id, forProduct])\n```\n\n========================================\n\nCode:\n```text\ntype Product {\n  id: ID! @unique\n  title: String!\n  reviews: [ProductReview!]! @relation(name: \"ProductReviews\", onDelete: CASCADE)\n}\n\ntype Customer {\n  id: ID! @unique\n  email: String @unique\n}\n\ntype ProductReview {\n  id: ID! @unique\n  forProduct: Product! @relation(name: \"ProductReviews\", onDelete: SET_NULL)\n  byCustomer: Customer!\n  review: String!\n  ratinng: Float!\n}\n```\n\n```text\nCustomer\n```\n\n```text\nProduct\n```\n\n```text\nProductReview\n```\n\n```text\nasync function vote(parent, args, context, info) {\n  // 1\n  const userId = getUserId(context)\n\n  // 2\n  const linkExists = await context.db.exists.Vote({\n    user: { id: userId },\n    link: { id: args.linkId },\n  })\n  if (linkExists) {\n    throw new Error(`Already voted for link: ${args.linkId}`)\n  }\n\n  // 3\n  return context.db.mutation.createVote(\n    {\n      data: {\n        user: { connect: { id: userId } },\n        link: { connect: { id: args.linkId } },\n      },\n    },\n    info,\n  )\n}\n```\n\n```text\nUser\n```\n\n```text\nLink\n```\n\n```text\nVote\n```\n\n```text\nVote\n```\n\n```text\nALTER TABLE ProductReview ADD UNIQUE KEY uk_cust_prod (customer_id, product_id);\n```\n\n```text\n(cusotmer_id, product_id)\n```\n\n```text\nProductReview\n```\n\n```text\ntype Product {\nid: ID! @unique\n  title: String!\n  reviews: [ProductReview!]! @relation(name: \"ProductReviews\", onDelete: CASCADE)\n}\n\ntype Customer {\n  id: ID! @unique\n  email: String @unique\n}\n\ntype ProductReview {\n  id: ID! @unique\n  forProduct: Product! @relation(name: \"ProductReviews\", onDelete: SET_NULL)\n  byCustomer: Customer!\n  review: String!\n  ratinng: Float!\n  UniqueCustomerReview:String!  # adding a extra field\n}\n```\n\n```text\nmutation{\ncreateProductReview(\ndata:{\nforProduct: {\"connect\":{\"id\":\"<Replacec_with_product_id>\"}}\nbyCustomer: {\"connect\":{\"email\":\"<Replacec_with_customer_email>\"}}\nreview: \"my product review...\"\nratinng: 5.0\nUniqueCustomerReview:\"loggedInUser@email.com_<Poductid>\" # replace the string with user email and product id. this will create a unique product review for the user alone.\n      }\n                   )\n{\nUniqueCustomerReview\n# ... any requied fields\n}\n        }\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nmodel User {\n  firstName String\n  lastName  String\n  email     String\n\n  @@id([firstName, lastName])\n}\n```\n\n```text\n@@id([id, forProduct])\n```\n\n```text\nProductReview\n```\n\n========================================\n\nComments:\n- Thanks @tim, since Prisma doesn't support this, application level check seems the only way. Would you suggest a \"right way\" to handle this there?\n- Hi @nburk, so the idea is to handle this at the application server level for now. Got it! Have raised a feature request with the same body too. Thanks!\n- You should add `@unique` to the `UniqueCustomerReview: String!`","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":220,"estimatedTokens":1040}}123{"id":"stack-79370923","source":"stackoverflow","questionId":79370923,"title":"\"Next.js TypeScript error: 'param_type.params' incompatible with 'ParamCheck' during build\"","tags":["typescript","next.js","prisma","nextjs-api-router"],"text":"Title: \"Next.js TypeScript error: 'param_type.params' incompatible with 'ParamCheck' during build\"\nTags: typescript, next.js, prisma, nextjs-api-router\nSource: Stack Overflow\n\nQuestion:\nI am working on a Next.js project with TypeScript and Prisma. When running npm run build, the build fails with the following error:\n\n```\nType error: Type '{ __tag__: \"GET\"; __param_position__: \"second\"; __param_type__: { params: { id: string; }; }; }' does not satisfy the constraint 'ParamCheck'.\nThe types of '__param_type__.params' are incompatible between these types.\nType '{ id: string; }' is missing the following properties from type 'Promise': then, catch, finally, [Symbol.toStringTag]\n```\n\nError Context:\nFile causing issue: route.ts in app/api/projects/[id].\nRelevant Code: Here’s the snippet of the GET handler that seems to cause the issue:\n\nimport { NextResponse } from \"next/server\";\n\n```\nimport { prisma } from \"@/lib/prisma\";\n\nexport async function GET(\n request: Request,\n { params }: { params: { id: string } }\n) {\n try {\n const project = await prisma.project.findUnique({\n where: { id: params.id },\n });\n\n if (!project) {\n return NextResponse.json({ error: \"Project not found\" }, { status: 404 });\n }\n\n return NextResponse.json(project);\n } catch (error) {\n console.error(\"Error fetching project:\", error);\n return NextResponse.json({ error: \"Failed to fetch project\" }, { status: 500 });\n }\n}\n```\n\n**What I’ve Tried:**\n\nChecked tsconfig.json settings (strict mode enabled):\n\n{\n\"compilerOptions\": {\n\"strict\": true,\n\"moduleResolution\": \"node\",\n\"skipLibCheck\": true\n}\n}\n\nReinstalled node_modules and regenerated Prisma client:\n**\n\nrm -rf node_modules package-lock.json\nnpm install\nnpx prisma generate\n\n**\n**Project Versions:**\nNext.js: 15.1.2\nPrisma: 6.2.1\nTypeScript: 5.x\n\n========================================\n\nTop Answer:\n​In Next.js 15, there was a significant change in how route parameters (params) are handled in asynchronous components and functions. Previously, in versions like Next.js 14, params were accessed synchronously. However, starting from Next.js 15, params are now returned as a Promise, aligning with the framework's enhanced asynchronous data fetching capabilities. ​\nMedium\n\nUnderstanding the Issue:\n\nWhen upgrading to Next.js 15, developers might encounter a TypeScript error in their API routes similar to:\n\n\r\n\r\n\n```\nType error: Type '{ params: { id: string; }; }' does not satisfy the constraint 'PageProps'.\n Types of property 'params' are incompatible.\n Type '{ id: string; }' is missing the following properties from type 'Promise': then, catch, finally, [Symbol.toStringTag]\n```\n\n\r\n\r\n\r\n\nThis error arises because the params object, which was previously synchronous, is now asynchronous and returns a Promise. If the code does not account for this change by awaiting the params object, TypeScript will raise a type incompatibility error.\n\nTo resolve this issue, you need to update your API route handlers to handle params as a Promise. Here's how you can modify your code:​\n\n\r\n\r\n\n```\nexport async function GET(\n request: Request,\n { params }: { params: Promise } // Note the Promise type\n) {\n try {\n const { id } = await params; // Await the params to resolve the Promise\n```\n\n\r\n\r\n\r\n\nBy updating your code to treat params as a Promise, you can adapt to the changes introduced in Next.js 15 without the need for additional packages or complex modifications.\n\n========================================\n\nCode:\n```text\nType error: Type '{ __tag__: \"GET\"; __param_position__: \"second\"; __param_type__: { params: { id: string; }; }; }' does not satisfy the constraint 'ParamCheck<RouteContext>'.\nThe types of '__param_type__.params' are incompatible between these types.\nType '{ id: string; }' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag]\n```\n\n```text\nimport { prisma } from \"@/lib/prisma\";\n\nexport async function GET(\n  request: Request,\n  { params }: { params: { id: string } }\n) {\n  try {\n    const project = await prisma.project.findUnique({\n      where: { id: params.id },\n    });\n\n    if (!project) {\n      return NextResponse.json({ error: \"Project not found\" }, { status: 404 });\n    }\n\n    return NextResponse.json(project);\n  } catch (error) {\n    console.error(\"Error fetching project:\", error);\n    return NextResponse.json({ error: \"Failed to fetch project\" }, { status: 500 });\n  }\n}\n```\n\n```text\nexport async function GET(\n  request: Request,\n  {params}: { params: Promise<{ id: string }> }\n) {\n  const id = await params.id\n  // rest of your code\n}\n```\n\n```text\nparams\n```\n\n```text\nexport async function GET(\n  request: Request,\n  {params}: { params: Promise<{ id: string }> }\n) {\n  const id = (await params).id\n  // rest of your code\n}\n```\n\n```text\nparams\n```\n\n```js\nType error: Type '{ params: { id: string; }; }' does not satisfy the constraint 'PageProps'.\n  Types of property 'params' are incompatible.\n    Type '{ id: string; }' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag]\n```\n\n```js\nexport async function GET(\n  request: Request,\n  { params }: { params: Promise<{ id: string }> } // Note the Promise type\n) {\n  try {\n    const { id } = await params; // Await the params to resolve the Promise\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.828Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":188,"estimatedTokens":1318}}124{"id":"stack-62953062","source":"stackoverflow","questionId":62953062,"title":"Prisma throws an error \"TypeError: cannot read property findmany of undefined\"","tags":["javascript","node.js","graphql","prisma","prisma-graphql"],"text":"Title: Prisma throws an error \"TypeError: cannot read property findmany of undefined\"\nTags: javascript, node.js, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI wanted to make a chat app to practice working with graphql and node, for database I used prisma. I was doing everything like in this tutorial.\n\nhttps://www.howtographql.com/graphql-js/0-introduction/\n\nI just changed variable names.\n\nso I have this code\n\n```\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\n\nconst resolvers = {\n Query: {\n history: async (parent, args, context) => {\n return context.prisma.Messages.findMany()\n },\n },\n Mutation: {\n post: (parent, args, context) => {\n const newMessage = context.prisma.Messages.create({\n data: {\n username: args.username,\n message: args.message,\n },\n })\n return newMessage\n },\n },\n}\n\nconst server = new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context: {\n prisma,\n }\n})\nserver.start(() => console.log(`Server is running on http://localhost:4000`))\n```\n\nas my index.js\n\nthis is my schema.prisma\n\n```\nprovider = \"sqlite\"\n url = \"file:./dev.db\"\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Message {\n id Int @id @default(autoincrement())\n sendedAt DateTime @default(now())\n message String\n username String\n}\n```\n\nscript.js\n\n```\nconst { PrismaClient } = require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function main() {\n const newMessage = await prisma.Messages.create({\n data: {\n message: 'Fullstack tutorial for GraphQL',\n username: 'www.howtographql.com',\n },\n })\n const allMessages = await prisma.Messages.findMany()\n console.log(allMessages)\n}\n\nmain()\n .catch(e => {\n throw e\n })\n // 5\n .finally(async () => {\n await prisma.disconnect()\n })\n```\n\nand schema.graphql\n\n```\ntype Query {\n history: [Message!]!\n}\n\ntype Mutation {\n post(username: String!, message: String!): Message!\n}\n\ntype Message {\n id: ID!\n message: String!\n username: String!\n}\n```\n\nand that is what i got in my playground\n\n```\n\"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot read property 'findMany' of undefined\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"history\"\n ]\n }\n ]\n}\n```\n\nplease help\n\n========================================\n\nTop Answer:\nI managed to fix that. Actually, all I needed was to use the same name but lowercased as in schema.prisma\n\n========================================\n\nCode:\n```text\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\n\n\nconst resolvers = {\n  Query: {\n    history: async (parent, args, context) => {\n      return context.prisma.Messages.findMany()\n    },\n  },\n  Mutation: {\n    post: (parent, args, context) => {\n      const newMessage = context.prisma.Messages.create({\n        data: {\n          username: args.username,\n          message: args.message,\n        },\n      })\n      return newMessage\n    },\n  },\n}\n\nconst server = new GraphQLServer({\n  typeDefs: './src/schema.graphql',\n  resolvers,\n  context: {\n    prisma,\n  }\n})\nserver.start(() => console.log(`Server is running on http://localhost:4000`))\n```\n\n```text\nprovider = \"sqlite\"\n  url      = \"file:./dev.db\"\n}\n\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\n\nmodel Message {\n  id       Int      @id @default(autoincrement())\n  sendedAt DateTime @default(now())\n  message  String\n  username String\n}\n```\n\n```text\nconst { PrismaClient } = require(\"@prisma/client\")\n\n\nconst prisma = new PrismaClient()\n\n\nasync function main() {\n  const newMessage = await prisma.Messages.create({\n    data: {\n      message: 'Fullstack tutorial for GraphQL',\n      username: 'www.howtographql.com',\n    },\n  })\n  const allMessages = await prisma.Messages.findMany()\n  console.log(allMessages)\n}\n\n\nmain()\n  .catch(e => {\n    throw e\n  })\n  // 5\n  .finally(async () => {\n    await prisma.disconnect()\n  })\n```\n\n```text\ntype Query {\n  history: [Message!]!\n}\n\ntype Mutation {\n  post(username: String!, message: String!): Message!\n}\n\ntype Message {\n  id: ID!\n  message: String!\n  username: String!\n}\n```\n\n```text\n\"data\": null,\n  \"errors\": [\n    {\n      \"message\": \"Cannot read property 'findMany' of undefined\",\n      \"locations\": [\n        {\n          \"line\": 2,\n          \"column\": 3\n        }\n      ],\n      \"path\": [\n        \"history\"\n      ]\n    }\n  ]\n}\n```\n\n```text\nMessage\n```\n\n```text\nmessage\n```\n\n```text\nMessagePerUser\n```\n\n```text\nmessagePerUser\n```\n\n```text\nStudentData\n```\n\n```text\nstudentData\n```\n\n========================================\n\nComments:\n- Developing a Shopify App using remix / Prisma, I faced the same. Just had to restart the `shopify app dev` command to update Prisma with new migrations, even if I use `prisma generate`.\n- The same name for what – can you elaborate what exactly was the error?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Hello, please don't post code only and add an explantation as to why you think that this is the optimal solution. People are supposed to learn from your answer, which might not occur if they just copy paste code without knowing why it should be used.","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":292,"estimatedTokens":1315}}125{"id":"stack-71892875","source":"stackoverflow","questionId":71892875,"title":"Prisma migrate on an altered DB","tags":["prisma"],"text":"Title: Prisma migrate on an altered DB\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nGiven a team composed of data scientists and developers.\n\nDevelopers want to use `schema.prisma` but data scientists don't and want to freely edit the DB directly...\n\nWhat happen if a data scientist alter the DB directly? Will `prisma migrate dev/deploy` continue to work correctly?\n\n========================================\n\nTop Answer:\nIn addition to @Nurul Sundarani's answer, here is what I did:\n\n```\n$ vim .env # Points `DATABASE_URL` to the data-scientists' DB\n$ npx prisma db pull # Pull changes from it and update `schema.prisma`\n\n$ vim .env # Points `DATABASE_URL` back to localhost\n$ npx prisma migrate dev # Generate the migration and apply changes tolocal DB\nName of your migration: my_sneaky_new_migration\n\n$ git add prisma/schema.prisma prisma/migrations/20220603XXXXX_my_sneaky_new_migration\n$ git commit\n\n$ vim .env # Points `DATABASE_URL` to the data-scientists' DB\n$ npx prisma migrate resolve --applied \"my_sneaky_new_migration\" # Mark the migration as already applied\n\n$ vim .env # Points `DATABASE_URL` back to localhost\n```\n\n========================================\n\nCode:\n```text\nschema.prisma\n```\n\n```text\nprisma migrate dev/deploy\n```\n\n```text\nprisma migrate dev\n```\n\n```text\n$ vim .env # Points `DATABASE_URL` to the data-scientists' DB\n$ npx prisma db pull # Pull changes from it and update `schema.prisma`\n\n$ vim .env # Points `DATABASE_URL` back to localhost\n$ npx prisma migrate dev # Generate the migration and apply changes tolocal DB\nName of your migration: my_sneaky_new_migration\n\n$ git add prisma/schema.prisma prisma/migrations/20220603XXXXX_my_sneaky_new_migration\n$ git commit\n\n$ vim .env # Points `DATABASE_URL` to the data-scientists' DB\n$ npx prisma migrate resolve --applied \"my_sneaky_new_migration\" # Mark the migration as already applied\n\n$ vim .env # Points `DATABASE_URL` back to localhost\n```\n\n========================================\n\nComments:\n- Thank you, very interesting! And what about `prisma migrate deploy` when a such drift exists?","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":69,"estimatedTokens":519}}126{"id":"stack-73417985","source":"stackoverflow","questionId":73417985,"title":"How can I export my model's properties types from Prisma Schema?","tags":["javascript","node.js","prisma"],"text":"Title: How can I export my model's properties types from Prisma Schema?\nTags: javascript, node.js, prisma\nSource: Stack Overflow\n\nQuestion:\nLets say I have this Prisma Schema :\n\n```\nmodel User {\n id String @id @unique @default(dbgenerated(\"gen_random_uuid()\")) @db.Uuid\n email String @unique\n username String \n}\n```\n\nIs there a way I can get lets say **email's type** in my app ?\n\n- One options I can come with is a file that will export types but that way everytime I make a change to my prisma schema I will have to go there and manually edit the type.\n\n========================================\n\nCode:\n```text\nmodel User {\n  id             String   @id @unique @default(dbgenerated(\"gen_random_uuid()\")) @db.Uuid\n  email          String   @unique\n  username       String   \n}\n```\n\n```js\nimport { PrismaClient, User } from '@prisma/client';\n```\n\n```text\nnpx prisma generate\n```\n\n========================================\n\nComments:\n- Oh thanks. I totaly forgot about that","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":42,"estimatedTokens":243}}127{"id":"stack-61583460","source":"stackoverflow","questionId":61583460,"title":"Prisma 2 query to return records only that are associated with ALL of the provided tag IDs","tags":["react-apollo","apollo-server","prisma","prisma-graphql","redwoodjs"],"text":"Title: Prisma 2 query to return records only that are associated with ALL of the provided tag IDs\nTags: react-apollo, apollo-server, prisma, prisma-graphql, redwoodjs\nSource: Stack Overflow\n\nQuestion:\nI have tables Principles and Tags. And there is a many-to-many relation between them (joined implicitly).\n\nWithout using `prisma.raw`, how can I run the following query?\n\n```\nSELECT p.id, p.title, p.description, p.createdAt, p.modifiedAt\n FROM principle p\n WHERE EXISTS (SELECT NULL\n FROM _PrincipleToTag pt\n WHERE pt.B IN (${tagIds.join(',')})\n AND pt.A = p.id\n GROUP BY pt.A\n HAVING COUNT(DISTINCT pt.B) = ${tagIds.length})\n```\n\n**How can I update this Prisma 2 query such that the principles returned are only principles that are associated with ALL of the provided tagIds?**\n\n```\nexport const principles = ({ tagIds }) => {\n const payload = {\n where: {\n //TODO filter based on tagIds\n },\n }\n return db.principle.findMany(payload)\n}\n```\n\nThe docs mention `contains` and `in` and `every`, but I can't find examples of what I'm trying to do.\n\nI'm using RedwoodJs, Prisma 2, Apollo, GraphQL.\n\n**Update** in response to comment: here is the SDL:\n\n```\ninput CreatePrincipleInput {\n title: String!\n description: String\n}\n\ninput CreatePrincipleWithTagsInput {\n title: String!\n description: String\n tagIdsJson: String\n}\n\ninput CreateTagInput {\n title: String!\n description: String\n}\n\n# A date string, such as 2007-12-03, compliant with the `full-date` format\n# outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for\n# representation of dates and times using the Gregorian calendar.\nscalar Date\n\n# A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the\n# `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO\n# 8601 standard for representation of dates and times using the Gregorian calendar.\nscalar DateTime\n\ntype Mutation {\n createPrinciple(input: CreatePrincipleInput!): Principle\n createPrincipleWithTags(input: CreatePrincipleWithTagsInput!): Principle\n updatePrinciple(id: Int!, input: UpdatePrincipleInput!): Principle!\n deletePrinciple(id: Int!): Principle!\n createTag(input: CreateTagInput!): Tag!\n updateTag(id: Int!, input: UpdateTagInput!): Tag!\n deleteTag(id: Int!): Tag!\n}\n\ntype Principle {\n id: Int!\n title: String!\n description: String!\n tags: [Tag]\n createdAt: DateTime!\n modifiedAt: DateTime!\n}\n\ntype Query {\n redwood: Redwood\n principles(searchQuery: String, tagIds: [Int]): [Principle!]!\n tags: [Tag!]!\n tagsByLabel(searchTerm: String): [TagCount!]!\n tag(id: Int!): Tag!\n}\n\ntype Redwood {\n version: String\n}\n\ntype Tag {\n id: Int!\n title: String!\n principles: [Principle]\n description: String\n createdAt: DateTime!\n modifiedAt: DateTime!\n}\n\ntype TagCount {\n id: Int!\n title: String!\n count: Int!\n principles: [Principle]\n description: String\n createdAt: DateTime!\n modifiedAt: DateTime!\n}\n\n# A time string at UTC, such as 10:15:30Z, compliant with the `full-time` format\n# outlined in section 5.6 of the RFC 3339profile of the ISO 8601 standard for\n# representation of dates and times using the Gregorian calendar.\nscalar Time\n\ninput UpdatePrincipleInput {\n title: String\n description: String\n}\n\ninput UpdateTagInput {\n title: String\n description: String\n}\n```\n\n========================================\n\nTop Answer:\nYou could try something like this\n\n```\nexport const principles = ({ searchQuery, tagIds }) => {\n const payload = {\n where: {\n OR: [\n { title: { contains: searchQuery } },\n { description: { contains: searchQuery } },\n ],\n // using the `in` operator like this\n tagId: { in: tagIds },\n userId: userIdFromSession,\n },\n }\n console.log('db.principle.findMany(payload)', payload)\n return db.principle.findMany(payload)\n}\n```\n\nThat should do the trick!\n\n========================================\n\nCode:\n```sql\nSELECT p.id, p.title, p.description, p.createdAt, p.modifiedAt\n    FROM principle p\n   WHERE EXISTS (SELECT NULL\n                   FROM _PrincipleToTag pt\n                  WHERE pt.B IN (${tagIds.join(',')})\n                    AND pt.A = p.id\n               GROUP BY pt.A\n                 HAVING COUNT(DISTINCT pt.B) = ${tagIds.length})\n```\n\n```js\nexport const principles = ({ tagIds }) => {\n  const payload = {\n    where: {\n      //TODO filter based on tagIds\n    },\n  }\n  return db.principle.findMany(payload)\n}\n```\n\n```js\ninput CreatePrincipleInput {\n  title: String!\n  description: String\n}\n\ninput CreatePrincipleWithTagsInput {\n  title: String!\n  description: String\n  tagIdsJson: String\n}\n\ninput CreateTagInput {\n  title: String!\n  description: String\n}\n\n# A date string, such as 2007-12-03, compliant with the `full-date` format\n# outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for\n# representation of dates and times using the Gregorian calendar.\nscalar Date\n\n# A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the\n# `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO\n# 8601 standard for representation of dates and times using the Gregorian calendar.\nscalar DateTime\n\ntype Mutation {\n  createPrinciple(input: CreatePrincipleInput!): Principle\n  createPrincipleWithTags(input: CreatePrincipleWithTagsInput!): Principle\n  updatePrinciple(id: Int!, input: UpdatePrincipleInput!): Principle!\n  deletePrinciple(id: Int!): Principle!\n  createTag(input: CreateTagInput!): Tag!\n  updateTag(id: Int!, input: UpdateTagInput!): Tag!\n  deleteTag(id: Int!): Tag!\n}\n\ntype Principle {\n  id: Int!\n  title: String!\n  description: String!\n  tags: [Tag]\n  createdAt: DateTime!\n  modifiedAt: DateTime!\n}\n\ntype Query {\n  redwood: Redwood\n  principles(searchQuery: String, tagIds: [Int]): [Principle!]!\n  tags: [Tag!]!\n  tagsByLabel(searchTerm: String): [TagCount!]!\n  tag(id: Int!): Tag!\n}\n\ntype Redwood {\n  version: String\n}\n\ntype Tag {\n  id: Int!\n  title: String!\n  principles: [Principle]\n  description: String\n  createdAt: DateTime!\n  modifiedAt: DateTime!\n}\n\ntype TagCount {\n  id: Int!\n  title: String!\n  count: Int!\n  principles: [Principle]\n  description: String\n  createdAt: DateTime!\n  modifiedAt: DateTime!\n}\n\n# A time string at UTC, such as 10:15:30Z, compliant with the `full-time` format\n# outlined in section 5.6 of the RFC 3339profile of the ISO 8601 standard for\n# representation of dates and times using the Gregorian calendar.\nscalar Time\n\ninput UpdatePrincipleInput {\n  title: String\n  description: String\n}\n\ninput UpdateTagInput {\n  title: String\n  description: String\n}\n```\n\n```text\nprisma.raw\n```\n\n```text\ncontains\n```\n\n```text\nin\n```\n\n```text\nevery\n```\n\n```text\nexport const principles = async ({ searchQuery, tagIds }) => {      \n  const payload = {\n    where: {\n      OR: [\n        { title: { contains: searchQuery } },\n        { description: { contains: searchQuery } },\n      ],\n      userId: userIdFromSession,\n    },\n  }\n  if (tagIds.length) {\n    const whereAnd = []\n    tagIds.forEach((tagId) => {\n      whereAnd.push({\n        tags: { some: { id: tagId } },\n      })\n    })\n    payload.where.AND = whereAnd\n  }\n  const result = await db.principle.findMany(payload)\n  return result\n}\n```\n\n```js\nexport const principles = ({ searchQuery, tagIds }) => {\n  const payload = {\n    where: {\n      OR: [\n        { title: { contains: searchQuery } },\n        { description: { contains: searchQuery } },\n      ],\n      // using the `in` operator like this\n      tagId: { in: tagIds },\n      userId: userIdFromSession,\n    },\n  }\n  console.log('db.principle.findMany(payload)', payload)\n  return db.principle.findMany(payload)\n}\n```\n\n```js\nconst tagIds = [9,6];\n\nwhere: {\n  // ...\n  AND: tagIds.map(tagId => ({\n    tags: {\n      some: {\n        id: {\n          equals: tagId,\n        },\n      },\n    },\n  })),\n}\n```\n\n```text\nAND\n```\n\n========================================\n\nComments:\n- Thank you so much for your response. I tried it and updated my question with the error message. I'd love to hear any other ideas if you have a moment. Thanks again!\n- You would have to use `tags` as per your model. `tagId` was just a placeholder as I wasn't aware of your model field. Sorry for not mentioning that earlier.\n- I appreciate your effort, but this still isn't correct. I'd think I'd need to use both `every` and `in`, maybe like this: `{\"where\":{\"OR\":[{\"title\":{\"contains\":\"\"}},{\"description\":{\"c&zwnj;&#8203;ontains\":\"\"}}],\"user&zwnj;&#8203;Id\":1,\"tag\":{\"every\"&zwnj;&#8203;:[{\"id\":{\"in\":[9,6]}&zwnj;&#8203;},{\"id\":{\"in\":[9,6]}&zwnj;&#8203;}]}}}` either with `tag` singular or `tags` plural. But I'm getting errors \"Unknown arg `tag` in where.tag for type PrincipleWhereInput\" or \"Unknown arg `0` in where.tags.every.0 for type TagWhereInput.\"\n- I simplified my question above by showing the raw query that is the equivalent of what I'm trying to achieve. As stackoverflow.com/a/3876276/470749 explains, it allows me to retrieve only principles that are associated with *all* of the supplied tagIds. If you have any ideas, I'd appreciate them. Thanks.\n- How about this one? `db.principle.findMany({ where: { OR: [ { title: { contains: searchQuery }, }, { description: { contains: searchQuery }, }, ], tags: { every: { id: { in: tagIds, }, }, }, }, })`\n- Thank you so much for your response. That query runs without error, but the result isn't what I'm hoping for. I'll add a bounty to this question. I'd really like to figure this out.\n- I get error \"Unknown arg `tagId_some` in where.AND.0.tagId_some for type PrincipleWhereInput.\" when I use this `const whereAnd = [] tagIds.forEach((tagId) => { whereAnd.push({ tagId_some: { tagId: tagId }, }) })`\n- can you post your graphql schema from your playground\n- I updated my question to add the GraphQL schema. Thanks for looking at it.\n- Any last ideas? I'm supposed to award the bounty soon. Thanks in advance!\n- Thank you! I adjusted your answer to what I'm using now, and it seems to work! I really appreciate your help.","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":369,"estimatedTokens":2465}}128{"id":"stack-72100627","source":"stackoverflow","questionId":72100627,"title":"Prisma: update nested entities in a single query","tags":["javascript","mysql","node.js","prisma"],"text":"Title: Prisma: update nested entities in a single query\nTags: javascript, mysql, node.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using Prisma and Express.js to make requests to my MySQL database table.\n\nI have one-to-many relationship between my **Contest-Round** tables and am trying to\nwrite a query which would allow me to differently update rounds for a given contest.\nGiven the schema:\n\n```\nmodel Contest {\n id Int @id @default(autoincrement())\n name String @unique\n rounds Round[]\n ... other fields\n}\n\nmodel Round {\n id Int @id @default(autoincrement())\n name String\n contestId Int\n contest Contest @relation(fields: [contestId], references: [id], onDelete: Cascade)\n ... other fields\n}\n```\n\nWhat I want to achieve is to update the contest from\n\n```\n{\n id: 100,\n name: 'contest1',\n rounds: [\n {\n id: 1,\n name: 'round1',\n contestId: 100,\n },\n {\n id: 2,\n name: 'round2',\n contestId: 100,\n }\n ]\n```\n\nto for example\n\n```\n{\n id: 100,\n name: 'contest1',\n rounds: [\n {\n id: 1,\n name: 'round1Updated',\n contestId: 100,\n },\n {\n id: 2,\n name: 'round2UpdatedDifferently',\n contestId: 100,\n }\n ]\n```\n\nwhere the round names I get from the form value from HTML.\n\nI haven't found any examples on updating different nested entities, so I'm expecting it to be something like this:\n\n```\nvar updated = await prisma.contest.update({\n where: {\n id: 100\n },\n data: {\n name: data.name,\n rounds: {\n update: {\n where: {\n id: { in: [1, 2] },\n },\n data: {\n name: ['round1Updated', 'round2UpdatedDifferently'] \n },\n },\n }\n },\n include: {\n rounds: true,\n }\n });\n```\n\nAny ideas or clues would be appreciated.\n\n========================================\n\nTop Answer:\nWill something like this work?\n\n```\nconst updated = await prisma.contest.update({\n where: { id: 100 },\n data: {\n name: data.name,\n rounds: {\n deleteMany: { id: { in: [1, 2] } }, // Delete existing records first\n createMany: { // Update by creating new records\n data: [\n { id: 1, name: \"round1Updated\" },\n { id: 2, name: \"round2UpdatedDifferently\" },\n ]\n }\n }\n },\n include: { rounds: true }\n});\n```\n\nFrom form data\n\n```\nconst updated = await prisma.contest.update({\n where: { id: data.id },\n data: {\n name: data.name,\n rounds: {\n deleteMany: { id: { in: data.rounds.map(({ id }) => id) } },\n createMany: { data: rounds }\n }\n },\n include: { rounds: true }\n});\n```\n\nNote that the ordering of operations do matter:\n\nhttps://github.com/prisma/prisma/discussions/6263\n\n========================================\n\nCode:\n```text\nmodel Contest {\n    id            Int      @id @default(autoincrement())\n    name          String   @unique\n    rounds        Round[]\n    ... other fields\n}\n\nmodel Round {\n    id        Int       @id @default(autoincrement())\n    name      String\n    contestId Int\n    contest   Contest   @relation(fields: [contestId], references: [id], onDelete: Cascade)\n    ... other fields\n}\n```\n\n```text\n{\n    id: 100,\n    name: 'contest1',\n    rounds: [\n        {\n             id: 1,\n             name: 'round1',\n             contestId: 100,\n        },\n        {\n             id: 2,\n             name: 'round2',\n             contestId: 100,\n        }\n    ]\n```\n\n```text\n{\n    id: 100,\n    name: 'contest1',\n    rounds: [\n        {\n             id: 1,\n             name: 'round1Updated',\n             contestId: 100,\n        },\n        {\n             id: 2,\n             name: 'round2UpdatedDifferently',\n             contestId: 100,\n        }\n    ]\n```\n\n```text\nvar updated = await prisma.contest.update({\n            where: {\n                id: 100\n            },\n            data: {\n                name: data.name,\n                rounds: {\n                    update: {\n                        where: {\n                            id: { in: [1, 2] },\n                        },\n                        data: {\n                            name: ['round1Updated', 'round2UpdatedDifferently']   \n                        },\n                    },\n                }\n            },\n            include: {\n                rounds: true,\n            }\n        });\n```\n\n```text\n// get the target contest first\ncontes contest = await prisma.contest.findFirst({\n  where: { id },\n  select: {\n    rounds: true,\n  }\n});\n\n// newly created round on my form\nconst roundsToBeCreated = // rounds that the existing contest doesn't have yet, but the form does\n\n// deleted rounds on my form\nconst roundsToBeDeleted = // rounds that the existing contest has, but form data doesn't\n\nconst updated = await prisma.contest.update({ where: { id },\n        data: {\n            rounds: {\n                deleteMany: {\n                    id: {\n                        in: roundsToBeDeleted.map(r => r.id)\n                    },\n                },\n                createMany: {\n                    data: roundsToBeCreated\n                },\n            }\n        }\n    });\n```\n\n```text\nconst updated = await prisma.contest.update({\n  where: { id: 100 },\n  data: {\n    name: data.name,\n    rounds: {\n      deleteMany: { id: { in: [1, 2] } }, // Delete existing records first\n      createMany: { // Update by creating new records\n        data: [\n          { id: 1, name: \"round1Updated\" },\n          { id: 2, name: \"round2UpdatedDifferently\" },\n        ]\n      }\n    }\n  },\n  include: { rounds: true }\n});\n```\n\n```text\nconst updated = await prisma.contest.update({\n  where: { id: data.id },\n  data: {\n    name: data.name,\n    rounds: {\n      deleteMany: { id: { in: data.rounds.map(({ id }) => id) } },\n      createMany: { data: rounds }\n    }\n  },\n  include: { rounds: true }\n});\n```\n\n```text\nconst updated = await prisma.contest.update({\n  where: {id: data.id},\n  data: {\n    name: data.name,\n    rounds: {\n      deleteMany: {},\n      createMany: {data: rounds},\n    }\n  },\n  include: {rounds: true},\n});\n```\n\n```text\nconst result = await prisma.survey.upsert({\n            where: { id: parsedSurvey.data.id || 0 },\n            create: {\n                ...survey,\n                accountId,\n                questions: {\n                    create: questions\n                }\n            },\n            update: {\n                ...survey,\n                questions: {\n                    updateMany: questions.map((question, index) => ({\n                        where: { id: question.id || 0 },\n                        data: question\n                    })),\n                }\n            },\n        });\n```\n\n========================================\n\nComments:\n- Thanks, that partially solves my issue when my Rounds do not have related records in other tables or when I create a new Round in my form. But in case if I want to simply update a round name without loosing related records (e.g Results) I think I still need a separate query for updating Rounds\n- `where: { id: data.id }` - this is so strange that it's needed.\n- Hey is there no direct method of doing this instead of removing and adding back the updated nested entity?\n- Nest createMany is not implemented, how did you make it work? github.com/prisma/prisma/issues/5455","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":329,"estimatedTokens":1741}}129{"id":"stack-68291186","source":"stackoverflow","questionId":68291186,"title":"Prisma 2: Setting Minimum & Maximum Length of a String type","tags":["prisma","prisma2"],"text":"Title: Prisma 2: Setting Minimum & Maximum Length of a String type\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI am creating a model using Prisma 2 and want to set a minimum and maximum length for one of the fields. I.e., something like this:\n\n```\nmodel Post {\n ...\n title String @min(3) @max(240)\n ...\n}\n```\n\nI just made up the above syntax. I am wondering if something like that exists in Prisma and, if so, how to do it.\n\nAny ideas?\n\nThanks.\n\n========================================\n\nCode:\n```text\nmodel Post {\n ...\n title String @min(3) @max(240)\n ...\n}\n```\n\n```text\nmodel Post {\n ...\n title String @db.VarChar(240)\n ...\n}\n```\n\n```text\n@db.VarChar\n```\n\n```text\n@db.VarChar\n```\n\n========================================\n\nComments:\n- Thanks, that's what I needed to know.","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":52,"estimatedTokens":197}}130{"id":"stack-73899426","source":"stackoverflow","questionId":73899426,"title":"Implicit or Explicit Many to Many relationship in prisma","tags":["database","many-to-many","prisma","plumatic-schema"],"text":"Title: Implicit or Explicit Many to Many relationship in prisma\nTags: database, many-to-many, prisma, plumatic-schema\nSource: Stack Overflow\n\nQuestion:\nWhen should you use a implicit many to many relationship in prisma and when explicit many to many relationship ?\n\nDo they have any trade-off or anything that should be noted\n\n========================================\n\nCode:\n```text\nmodel Post {\n  id         Int        @id @default(autoincrement())\n  title      String\n  categories Category[]\n}\n\nmodel Category {\n  id    Int    @id @default(autoincrement())\n  name  String\n  posts Post[]\n}\n```\n\n```text\nmodel Post {\n  id         Int                 @id @default(autoincrement())\n  title      String\n  categories CategoriesOnPosts[]\n}\n\nmodel Category {\n  id    Int                 @id @default(autoincrement())\n  name  String\n  posts CategoriesOnPosts[]\n}\n\nmodel CategoriesOnPosts {\n  post       Post     @relation(fields: [postId], references: [id])\n  postId     Int\n  category   Category @relation(fields: [categoryId], references: [id])\n  categoryId Int \n\n  assignedAt DateTime @default(now())\n\n  @@id([postId, categoryId])\n}\n```\n\n```text\nPost\n```\n\n```text\nCategory\n```\n\n```text\nPost\n```\n\n```text\nCategory\n```\n\n```text\nconnect\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":309}}131{"id":"stack-74970815","source":"stackoverflow","questionId":74970815,"title":"I just got an error \"PrismaClient is unable to be run in the browser\" [next js]","tags":["javascript","next.js","prisma"],"text":"Title: I just got an error \"PrismaClient is unable to be run in the browser\" [next js]\nTags: javascript, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI was just going to console log all the id of news in my database. but when I run it and it throw an error like in this picture. How should I fix or solve this?\nhttps://i.sstatic.net/ci8G1.png\n\n========================================\n\nComments:\n- This might be helpful too, prisma.io/nextjs\n- If you are trying to use prisma in any actions.ts file then see if you have added \"use server\" at the start of the client. Prisma cannot be called on the frontend.\n- You can use prisma in server actions as well as api routes. However, if you intend on using it as a server action, make sure your actions.ts file does not reside anywhere in your app directory. Create a folder called server and place it directly in the /src directory.\n- API Routes have been replaced by Route Handlers in Next.js 13.2 according to the beta documentation. How can we use Prisma with route handlers?\n- @SamHeyman it's exactly the same, Route Handlers are just the name for API routes when using the App directory. they're the same thing","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":16,"estimatedTokens":292}}132{"id":"stack-74771680","source":"stackoverflow","questionId":74771680,"title":"Production build fails: Type error: Property 'companies' does not exist on type 'PrismaClient ...... whereas local build passes","tags":["typescript","next.js","prisma"],"text":"Title: Production build fails: Type error: Property 'companies' does not exist on type 'PrismaClient ...... whereas local build passes\nTags: typescript, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am building a nextjs project on vercel with typescript and prisma.\nVersions:\n\"next\": \"13.0.3\"\n\"typescript\": \"4.9.3\"\n\"prisma\": \"^4.6.1\"\n\nbuild is passing locally, but fails on vercel:\n\n```\nType error: Property 'companies' does not exist on type 'PrismaClient'.\n--\n01:05:17.287 |  \n01:05:17.287 | 71 \\| },\n01:05:17.288 | 72 \\| companies: async () => {\n01:05:17.288 | > 73 \\| const companies = await prisma.companies.findMany();\n01:05:17.289 | \\| ^\n01:05:17.289 | 74 \\| return companies;\n01:05:17.289 | 75 \\| },\n01:05:17.289 | 76 \\| },\n```\n\nwhereas typescript detects 'companies' as property of prisma\ntried to regenerate Prisma Client, deleting the model and consequently using: prisma format, prisma generate, prisma db push.\nI am using mongodb\n\n./prisma/schema.prisma\n\n```\nmodel companies {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n v Int? @map(\"__v\")\n name String\n}\n```\n\nproduction builds were passing before adding this new model\n\n========================================\n\nTop Answer:\nWrite the build command as :\n\n```\nnpx primsa generate && npm run build\n```\n\n========================================\n\nCode:\n```text\nType error: Property 'companies' does not exist on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound \\| RejectPerOperation \\| undefined>'.\n--\n01:05:17.287 |  \n01:05:17.287 | 71 \\|     },\n01:05:17.288 | 72 \\|     companies: async () => {\n01:05:17.288 | > 73 \\|       const companies = await prisma.companies.findMany();\n01:05:17.289 | \\|                                      ^\n01:05:17.289 | 74 \\|       return companies;\n01:05:17.289 | 75 \\|     },\n01:05:17.289 | 76 \\|   },\n```\n\n```text\nmodel companies {\n  id   String @id @default(auto()) @map(\"_id\") @db.ObjectId\n  v    Int?   @map(\"__v\")\n  name String\n}\n```\n\n```json\n{\n  \"name\": \"deployment-example-prisma-vercel\",\n  \"dependencies\": {\n    \"@prisma/client\": \"4.7.1\",\n    \"next\": \"13.0.6\",\n    \"react\": \"18.2.0\",\n    \"react-dom\": \"18.2.0\"\n  },\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"start\": \"next start\",\n    \"vercel-build\": \"prisma generate && prisma migrate deploy && next build\",\n    \"prisma:generate\": \"prisma generate\"\n  },\n  \"devDependencies\": {\n    \"prisma\": \"4.7.1\"\n  }\n}\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"start\": \"next start\",\n    \"lint\": \"next lint\",\n    \"postinstall\": \"prisma generate\"\n   },\n  \"devDependencies\": {\n    // ...\n  }\n```\n\n```text\npostinstall\n```\n\n```text\npackage.json\n```\n\n```text\nnpx primsa generate && npm run build\n```\n\n```js\n\"vercel-build\": \"prisma generate && prisma db push && next build\",\n\"prisma:generate\": \"prisma generate\"\n```\n\n```js\n\"vercel-build\": \"prisma generate && prisma migrate deploy && next build\",\n\"prisma:generate\": \"prisma generate\"\n```\n\n========================================\n\nComments:\n- That's interesting. I see `vercel-build` mentioned here stackoverflow.com/a/70745163/470749 which links to prisma.io/docs/guides/deployment/deployment-guides/&hellip; Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:14.829Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":140,"estimatedTokens":808}}133{"id":"stack-67218109","source":"stackoverflow","questionId":67218109,"title":"Get properties of a type","tags":["typescript","prisma"],"text":"Title: Get properties of a type\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI can't find a way to lookup in runtime whether a certain property exists on a type. Like so (pseudocode)\n\n```\nimport { MyType } from '@prisma/client';\n\nMyType.hasProperty(\"foo\") // true/false\n\nMyType.allProperties() // [\"foo\", \"bar\", \"stuff\"]\n```\n\nDoes anyone know a good solution? Thank you in advance !\n\n========================================\n\nCode:\n```text\nimport { MyType } from '@prisma/client';\n\nMyType.hasProperty(\"foo\") // true/false\n\nMyType.allProperties() // [\"foo\", \"bar\", \"stuff\"]\n```\n\n```text\nconst foo = { a: 123, b: 'bar' }\n'a' in foo // true\nObject.keys(foo) // ['a', 'b']\n```\n\n```text\nin\n```\n\n```text\nObject.keys(someObj)\n```\n\n========================================\n\nComments:\n- As a purely typescript question this is not possible, but maybe it can be done with the Prisma object? I’m adding the Prisma tag.\n- I've definitely wished I could do this before, but the philosophy of TypeScript has always been that the typing system is a compile-time only thing, with no impact on the run-time environment. It would be great if you could optionally export some sort of run-time object associated with a type containing info about that type, however.","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":315}}134{"id":"stack-71251937","source":"stackoverflow","questionId":71251937,"title":"Error: P1001: Can't reach database server at `localhost`:`5200`","tags":["postgresql","docker","orm","prisma"],"text":"Title: Error: P1001: Can't reach database server at `localhost`:`5200`\nTags: postgresql, docker, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nTechnologies I use:\n\n- nestjs -> for backend\n\n- prisma -> for orm\n\n- postgresql -> database\n\nI'm trying to run these technologies using Docker but I'm running into the following issue:\n\n```\nprisma schema loaded from prisma/schema.prism\nDatasource \"db\": PostgreSQL database \"nestjs\", schema \"public\" at \"localhost:5200\"\nError: P1001: Can't reach database server at `localhost`:`5200`\nPlease make sure your database server is running at `localhost`:`5200`\n```\n\ndocker-compose.dev.yml\n\n```\nversion: '3.7'\nservices:\n db:\n image: postgres:12.9\n ports:\n - 5200:5432\n environment:\n POSTGRES_USER: postgres\n POSTGRES_PASSWORD: 123\n POSTGRES_DB: nestjs\n volumes:\n - database-data:/var/lib/postgresql/data\n networks:\n - sai\n restart: always\n\n test:\n container_name: test\n image: test\n build:\n context: .\n target: development\n dockerfile: Dockerfile\n command: npm run start:prod\n ports:\n - 3000:3000\n - 9229:9229\n networks:\n - sai\n volumes:\n - .:/usr/src/app\n - /usr/src/app/node_modules\n links:\n - db\n depends_on:\n - db\n restart: always\n\nnetworks:\n sai:\n driver: bridge\n\nvolumes:\n database-data:\n```\n\nNestjs does not see my locahost database on port 5200.\n\nDockerfile file:\n\n```\nFROM node:latest as development\nWORKDIR /usr/src/app\nCOPY package*.json ./\nRUN npm install --only=development\nCOPY . .\nRUN npm run build\n\nFROM node:latest as production\nARG NODE_ENV=production\nENV NODE_ENV=${NODE_ENV}\nWORKDIR /usr/src/app\nCOPY package*.json ./\nRUN npm install --only=production\nCOPY . .\nCOPY --from=development /usr/src/app/prisma ./prisma\nCOPY --from=development /usr/src/app/dist ./dist\nEXPOSE 3000\nCMD npm run start:prod\n```\n\nThe npm run start:prod command also corresponds to the following in the package.json file:\n\n```\n...\n \"generate:prisma\": \"npx prisma migrate dev --name init\",\n \"start:prod\": \"npm run generate:prisma && npm run dist/main\",\n...\n```\n\n========================================\n\nTop Answer:\nIn the docker compose I found:\n\n```\nservices:\n db-test:\n image: postgres:15.2\n ports:\n - \"5433:5432\"\n```\n\nand i connected to the db using: `localhost:5433`\n\n========================================\n\nCode:\n```text\nprisma schema loaded from prisma/schema.prism\nDatasource \"db\": PostgreSQL database \"nestjs\", schema \"public\" at \"localhost:5200\"\nError: P1001: Can't reach database server at `localhost`:`5200`\nPlease make sure your database server is running at `localhost`:`5200`\n```\n\n```text\nversion: '3.7'\nservices:\n  db:\n    image: postgres:12.9\n    ports:\n      - 5200:5432\n    environment:\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: 123\n      POSTGRES_DB: nestjs\n    volumes:\n      - database-data:/var/lib/postgresql/data\n    networks:\n      - sai\n    restart: always\n\n  test:\n    container_name: test\n    image: test\n    build:\n      context: .\n      target: development\n      dockerfile: Dockerfile\n    command: npm run start:prod\n    ports:\n      - 3000:3000\n      - 9229:9229\n    networks:\n      - sai\n    volumes:\n      - .:/usr/src/app\n      - /usr/src/app/node_modules\n    links:\n      - db\n    depends_on:\n      - db\n    restart: always\n\nnetworks:\n  sai:\n    driver: bridge\n\nvolumes:\n  database-data:\n```\n\n```text\nFROM node:latest as development\nWORKDIR /usr/src/app\nCOPY package*.json ./\nRUN npm install --only=development\nCOPY . .\nRUN npm run build\n\n\nFROM node:latest as production\nARG NODE_ENV=production\nENV NODE_ENV=${NODE_ENV}\nWORKDIR /usr/src/app\nCOPY package*.json ./\nRUN npm install --only=production\nCOPY . .\nCOPY --from=development /usr/src/app/prisma ./prisma\nCOPY --from=development /usr/src/app/dist ./dist\nEXPOSE 3000\nCMD npm run start:prod\n```\n\n```text\n...\n  \"generate:prisma\": \"npx prisma migrate dev --name init\",\n  \"start:prod\": \"npm run generate:prisma && npm run dist/main\",\n...\n```\n\n```text\nlocalhost:5200\n```\n\n```text\ndb:5432\n```\n\n```text\nservices:\n  db-test:\n    image: postgres:15.2\n    ports:\n      - \"5433:5432\"\n```\n\n```text\nlocalhost:5433\n```\n\n========================================\n\nComments:\n- I did what you said. This time I'm getting an error like this: Error: P1001: Can't reach database server at `db`:`5200`\n- You need to use port 5432. Not 5200.\n- Yeah yeah. it worked now. Thank you\n- It didn't work for me. I tried doing `db:5432` also. I also tried adding `?connect_timeout=300` as per some comments. But none of them worked for me. Did anyone resolved this issue\n- @SubashShrestha the name can vary depending on how you named your database container. In my case, I the database as `database` instead of `db`. So, in my case, I have to use `database:5432`. And of course, don't forget to use docker-compose tag `depends_on`\n- Yeah, I named the container as postgredb so I needed to use the same name for database URL too. Now it worked.","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":235,"estimatedTokens":1211}}135{"id":"stack-72566290","source":"stackoverflow","questionId":72566290,"title":"How to use where in in Prisma?","tags":["prisma","prisma2"],"text":"Title: How to use where in in Prisma?\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have made a query below that search user using two columns. But it seems not working properly, I assume it is querying the `where` clause in each column instead of both columns.\n\nIs there a way we could `where ~ in` for two or more columns?\n\n```\nconst users = [\n {\n user_id: 1,\n school_id: 11,\n ..\n },\n {\n user_id: 2,\n school_id: 22\n },\n ..\n]\n\nawait prisma.user.findMany({\n where: {\n AND: {\n user_id: {\n in: users.map(user => user.user_id)\n },\n school_id: {\n in: users.map(user => user.school_id)\n }\n }\n }\n})\n```\n\nThe problem it does not search for *both* `user_id` and `school_id`. Instead it search *either* of the two column. I will ask assistance of you guys, or do you have better approach with the same result. thanks.\n\n========================================\n\nCode:\n```text\nconst users = [\n  {\n    user_id: 1,\n    school_id: 11,\n    ..\n  },\n  {\n    user_id: 2,\n    school_id: 22\n  },\n  ..\n]\n\nawait prisma.user.findMany({\n  where: {\n    AND: {\n      user_id: {\n        in: users.map(user => user.user_id)\n      },\n      school_id: {\n        in: users.map(user => user.school_id)\n      }\n    }\n  }\n})\n```\n\n```text\nwhere\n```\n\n```text\nwhere ~ in\n```\n\n```text\nuser_id\n```\n\n```text\nschool_id\n```\n\n```js\nawait prisma.user.findMany({\n  where: {\n    user_id: {\n      in: users.map(user => user.user_id)\n    },\n    school_id: {\n      in: users.map(user => user.school_id)\n    }\n  }\n})\n```\n\n```text\nAND\n```\n\n```text\nAND\n```\n\n```text\nAND\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":110,"estimatedTokens":384}}136{"id":"stack-73957354","source":"stackoverflow","questionId":73957354,"title":"Filter query with Prisma using fields of relation (One-to-Many relation)","tags":["typescript","nestjs","prisma"],"text":"Title: Filter query with Prisma using fields of relation (One-to-Many relation)\nTags: typescript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI am having trouble writing a query with prisma that includes a filter on a model's relation's key.\n\n```\nmodel Car {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n plate String @unique\n place String\n\n bookings Booking[]\n\n @@map(\"cars\")\n}\n```\n\nMy booking model is the following :\n\n```\nmodel Booking{\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n place String\n\n startDate DateTime\n endDate DateTime\n\n carId Int\n car Car @relation(fields: [carId], references: [id])\n\n @@map(\"bookings\")\n}\n```\n\nI am having trouble expressing a query returning every car that respect a given criteria on startDate and endDate within their bookings relation/key. I would appreciate any idea or clue, thank you in advance.\n\n========================================\n\nCode:\n```text\nmodel Car {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  plate     String  @unique\n  place     String\n\n  bookings  Booking[]\n\n  @@map(\"cars\")\n}\n```\n\n```text\nmodel Booking{\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  place String\n\n  startDate DateTime\n  endDate   DateTime\n\n  carId Int\n  car   Car @relation(fields: [carId], references: [id])\n\n  @@map(\"bookings\")\n}\n```\n\n```js\nprisma.booking.findMany({ where: { startDate, endDate }, include: { car: true }})\n```\n\n```js\nprisma.car.findMany({ where: { bookings: { some: { startDate, endDate } } } });\n```\n\n```js\nprisma.car.findMany({\n  where: {\n    bookings: { some: { startDate: { gte: startDate }, endDate: { lte: endDate } } },\n  },\n});\n```\n\n```text\nstartDate\n```\n\n```text\nendDate\n```\n\n========================================\n\nComments:\n- You mean like: `prisma.booking.findMany({ where: { startDate, endDate }, include: { car: true }})`?\n- More like `prisma.car.findMany(}include bookings : {where: {condition on (startDate, endDate) }})` but can't figure it out...","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":550}}137{"id":"stack-70527741","source":"stackoverflow","questionId":70527741,"title":"How to delete a record and any relationship records in an explicit many to many relationship?","tags":["many-to-many","prisma"],"text":"Title: How to delete a record and any relationship records in an explicit many to many relationship?\nTags: many-to-many, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm struggling to find documentation for handling explicit many to many relationships in Prisma. So I have resorted to dev by Stackoverflow....\n\nI have a many to many relationship:\n\n```\nmodel Fight {\n id Int @id @default(autoincrement())\n name String\n fighters FighterFights[]\n}\n\nmodel Fighter {\n id Int @id @default(autoincrement())\n name String @unique\n fights FighterFights[]\n}\n\nmodel FighterFights {\n fighter Fighter @relation(fields: [fighterId], references: [id])\n fighterId Int\n fight Fight @relation(fields: [fightId], references: [id])\n fightId Int\n\n @@id([fighterId, fightId])\n}\n```\n\nI am trying to delete a fight and delete the relationship in FighterFights but not delete the actual fighter.\n\nI tried the following:\n\n```\nconst result = await prisma.fight.delete({\n where: {\n id: Number(id),\n },\n})\n```\n\nbut get the error:\n\n```\nPrismaClientKnownRequestError:\nInvalid `prisma.fight.delete()` invocation:\nForeign key constraint failed on the field: `FighterFights_fightId_fkey (index)`\n```\n\nI then also tried:\n\n```\nconst result = await prisma.fight.delete({\n where: { id: Number(id) },\n data: {\n fighterFights: {\n deleteMany: {\n where: { fightId: id },\n },\n },\n },\n})\n```\n\nBut I get the error:\n\n```\nPrismaClientValidationError:\nInvalid `prisma.fight.delete()` invocation:\n\n{\n where: {\n id: 1\n },\n data: {\n ~~~~\n fighterFights: {\n deleteMany: {\n where: {\n fightId: '1'\n }\n }\n }\n }\n}\n\nUnknown arg `data` in data for type Fight. Available args:\n\ntype deleteOneFight {\n where: FightWhereUniqueInput\n}\n```\n\nI also tried:\n\n```\nconst result = await prisma.fight.delete({\n where: {\n id: Number(id),\n },\n data: {\n fighterFights: {\n deleteMany: [{ fightId: { equals: Number(id) } }],\n },\n },\n})\n```\n\nbut get the error:\n\n```\nInvalid `prisma.fight.delete()` invocation:\n\n{\n where: {\n id: 1\n },\n data: {\n ~~~~\n fighterFights: {\n deleteMany: [\n {\n fightId: {\n equals: 1\n }\n }\n ]\n }\n }\n}\n\nUnknown arg `data` in data for type Fight. Available args:\n\ntype deleteOneFight {\n where: FightWhereUniqueInput\n}\n```\n\n========================================\n\nTop Answer:\nHere is the Prisma documentation to disconnect related fields\n\nFor single disconnect\n\n```\nconst updatePost = await prisma.user.update({\n where: {\n id: 16,\n },\n data: {\n posts: {\n disconnect: [{ id: 12 }, { id: 19 }],\n },\n },\n select: {\n posts: true,\n },\n})\n```\n\nTo disconnect all\n\n```\nconst updateUser = await prisma.user.update({\n where: {\n id: 16\n },\n data: {\n posts: {\n set: []\n }\n },\n include: {\n posts: true\n }\n})\n```\n\n========================================\n\nCode:\n```text\nmodel Fight {\n  id            Int     @id @default(autoincrement())\n  name          String\n  fighters      FighterFights[]\n}\n\nmodel Fighter {\n  id        Int     @id @default(autoincrement())\n  name      String  @unique\n  fights    FighterFights[]\n}\n\nmodel FighterFights {\n  fighter      Fighter  @relation(fields: [fighterId], references: [id])\n  fighterId    Int\n  fight        Fight    @relation(fields: [fightId], references: [id])\n  fightId      Int\n\n  @@id([fighterId, fightId])\n}\n```\n\n```text\nconst result = await prisma.fight.delete({\n  where: {\n    id: Number(id),\n  },\n})\n```\n\n```text\nPrismaClientKnownRequestError:\nInvalid `prisma.fight.delete()` invocation:\nForeign key constraint failed on the field: `FighterFights_fightId_fkey (index)`\n```\n\n```text\nconst result = await prisma.fight.delete({\n  where: { id: Number(id) },\n  data: {\n    fighterFights: {\n      deleteMany: {\n        where: { fightId: id },\n      },\n    },\n  },\n})\n```\n\n```text\nPrismaClientValidationError:\nInvalid `prisma.fight.delete()` invocation:\n\n{\n  where: {\n    id: 1\n  },\n  data: {\n  ~~~~\n    fighterFights: {\n      deleteMany: {\n        where: {\n          fightId: '1'\n        }\n      }\n    }\n  }\n}\n\nUnknown arg `data` in data for type Fight. Available args:\n\ntype deleteOneFight {\n  where: FightWhereUniqueInput\n}\n```\n\n```text\nconst result = await prisma.fight.delete({\n  where: {\n    id: Number(id),\n  },\n  data: {\n    fighterFights: {\n      deleteMany: [{ fightId: { equals: Number(id) } }],\n    },\n  },\n})\n```\n\n```text\nInvalid `prisma.fight.delete()` invocation:\n\n{\n  where: {\n    id: 1\n  },\n  data: {\n  ~~~~\n    fighterFights: {\n      deleteMany: [\n        {\n          fightId: {\n            equals: 1\n          }\n        }\n      ]\n    }\n  }\n}\n\nUnknown arg `data` in data for type Fight. Available args:\n\ntype deleteOneFight {\n  where: FightWhereUniqueInput\n}\n```\n\n```text\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\n\nconst saveData = async () => {\n  const fighter1 = await prisma.fighter.create({\n    data: {\n      name: 'Ryu',\n    },\n  })\n  const fighter2 = await prisma.fighter.create({\n    data: {\n      name: 'Ken',\n    },\n  })\n  console.log('FIGHTERS');\n  console.log(JSON.stringify(fighter1, null, 2));\n  console.log(JSON.stringify(fighter2, null, 2));\n\n  const fight = await prisma.fight.create({\n    data: {\n      name: 'Ryu vs Ken',\n      fighters: {\n        createMany: {\n          data: [\n            {\n              fighterId: fighter1.id,\n            },\n            {\n              fighterId: fighter2.id,\n            },\n          ]\n        },\n      },\n    },\n    select: {\n      id: true,\n      fighters: {\n        select: {\n          fighter: true,\n        },\n      },\n    },\n  });\n  console.log('FIGHTS');\n  console.log(JSON.stringify(await prisma.fight.findMany({ include: { fighters: true } }), null, 2));\n\n  const fighterFightsToDelete = prisma.fighterFights.deleteMany({\n    where: {\n      fightId: fight.id,\n    }\n  })\n\n  const fightToDelete = prisma.fight.delete({\n    where: {\n      id: fight.id,\n    }\n  })\n\n  await prisma.$transaction([ fighterFightsToDelete, fightToDelete ])\n  console.log('RESULT');\n  console.log(JSON.stringify(await prisma.fight.findMany({ include: { fighters: true } }), null, 2));\n  console.log(JSON.stringify(await prisma.fighter.findMany({ include: { fights: true } }), null, 2));\n}\n\nsaveData()\n```\n\n```text\nconst updatePost = await prisma.user.update({\n  where: {\n    id: 16,\n  },\n  data: {\n    posts: {\n      disconnect: [{ id: 12 }, { id: 19 }],\n    },\n  },\n  select: {\n    posts: true,\n  },\n})\n```\n\n```text\nconst updateUser = await prisma.user.update({\n  where: {\n    id: 16\n  },\n  data: {\n    posts: {\n      set: []\n    }\n  },\n  include: {\n    posts: true\n  }\n})\n```\n\n========================================\n\nComments:\n- how do i auto delete ?","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":407,"estimatedTokens":1633}}138{"id":"stack-69649981","source":"stackoverflow","questionId":69649981,"title":"error An unexpected error occurred: \"EPERM: operation not permitted, unlink 'path_to_project\\\\node_modules\\\\prisma\\\\query_engine-windows.dll.node'","tags":["javascript","package","yarnpkg","prisma"],"text":"Title: error An unexpected error occurred: \"EPERM: operation not permitted, unlink 'path_to_project\\\\node_modules\\\\prisma\\\\query_engine-windows.dll.node'\nTags: javascript, package, yarnpkg, prisma\nSource: Stack Overflow\n\nQuestion:\nI installed Prisma and I run `npx primsa db push` it pushed all tables to database successfully, after that I run `npx prisma generate` it tried to install @prisma/client and it fails with this error message:\n\nerror An unexpected error occurred: \"EPERM: operation not permitted, unlink 'path_to_project\\node_modules\\prisma\\query_engine-windows.dll.node'\n\nI tried to remove `node_modules` and re-install all modules but it not worked.\n\n========================================\n\nTop Answer:\nIf you are running **nextjs** server. Close the server and try running the command again.\n\n```\n$ npx prisma generate\n```\n\n========================================\n\nCode:\n```text\nnpx primsa db push\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnode_modules\n```\n\n```text\n@prisma/client\n```\n\n```text\nyarn add @prisma/client\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n$ npx prisma generate\n```\n\n```text\nnpx prisama generate\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n.prisma/client\n```\n\n```text\nctrl+c\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n<filePath>\n```\n\n```text\nCtrl+C\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnpx prisma migrate dev --name <name>\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n$ npx prisma generate\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nError: \nEPERM: operation not permitted, unlink 'D:\\Tutorials\\app\\app-backend\\node_modules\\.prisma\\client\\query_engine-windows.dll.node'\n```\n\n```text\nnpx prisma generate\n```\n\n```text\ndocker-compose up\n```\n\n```text\nPrisma\n```\n\n```text\nPrisma Studio\n```\n\n```text\nprisma\n```\n\n```text\nPrisma\n```\n\n========================================\n\nComments:\n- This solved the problem, thank you. I killed the prisma client and the app, then run my command and worked without issues.\n- I closed the running localhost:3000 , worked for me\n- I have issue with this command, `$ npx prisma migrate dev` . still loading\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- [Hash]Tags do not belong into answers. As you can see they do not render as linked. They have no effect. So they end up as noise. I'll edit-drop them from your answer.","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":131,"estimatedTokens":647}}139{"id":"stack-58822068","source":"stackoverflow","questionId":58822068,"title":"is it possible to define an interface in prisma?","tags":["go","graphql","prisma"],"text":"Title: is it possible to define an interface in prisma?\nTags: go, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to have a `\"generic\"` info in my object.\n\nBasically what I want to do is to have 2 different kinds of object, lets say `image` and `document`\n\nBoth have different fields except for the `ID`\n\nI was wondering what would be the best approach to define my `datamodel.prisma` so when I use my graphql model (in GO) I can use a generic interface like `data`\n\nIs it even possible? If not what solution could be the best?\n\nI know in graphql there are interfaces but Im not sure how to define it in prisma.\n\nIdeas?\n\n========================================\n\nCode:\n```text\n\"generic\"\n```\n\n```text\nimage\n```\n\n```text\ndocument\n```\n\n```text\nID\n```\n\n```text\ndatamodel.prisma\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- could be a possible solution for this?","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":50,"estimatedTokens":226}}140{"id":"stack-55571978","source":"stackoverflow","questionId":55571978,"title":"Is better pass prisma object through context to resolvers or use it directly?","tags":["graphql","apollo-server","prisma","prisma-graphql"],"text":"Title: Is better pass prisma object through context to resolvers or use it directly?\nTags: graphql, apollo-server, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI want to know if is better or there is any difference in use prisma client directly in resolvers or pass it through context.\n\nIn the official documentation it is passed through context:\n\n```\nconst { prisma } = require('./generated/prisma-client');\n\nconst resolvers = {\n Query: {\n feed: (parent, args, context) => {\n return context.prisma.posts({ where: { published: true } })\n }\n}\n\nconst server = new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context: {\n prisma,\n },\n})\n```\n\nMy question is: why prisma client is not used directly in resolvers.\n\n```\nconst { prisma } = require('./generated/prisma-client');\n\nconst resolvers = {\n Query: {\n feed: (parent, args, context) => {\n return prisma.posts({ where: { published: true } })\n }\n}\n\nconst server = new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n})\n```\n\nIs there anything wrong in this solution?\n\n========================================\n\nCode:\n```text\nconst { prisma } = require('./generated/prisma-client');\n\nconst resolvers = {\n  Query: {\n    feed: (parent, args, context) => {\n      return context.prisma.posts({ where: { published: true } })\n    }\n}\n\nconst server = new GraphQLServer({\n  typeDefs: './src/schema.graphql',\n  resolvers,\n  context: {\n    prisma,\n  },\n})\n```\n\n```text\nconst { prisma } = require('./generated/prisma-client');\n\nconst resolvers = {\n  Query: {\n    feed: (parent, args, context) => {\n      return prisma.posts({ where: { published: true } })\n    }\n}\n\nconst server = new GraphQLServer({\n  typeDefs: './src/schema.graphql',\n  resolvers,\n})\n```\n\n```text\ncontext.db1\n```\n\n```text\ncontext.db2\n```\n\n```text\nPrisma\n```\n\n========================================\n\nComments:\n- Moreover, you can create the context based on the request and therefore dynamically use of prisma instance or another in a multi-tenant architecture (see prisma-multi-tenant)\n- but how does one get intenseness to work when passing it via context.\n- Context always turns into a mess, and encourages a whole slew of anti-patterns. Over time you end up with so much garbage like \"does this variable exist on the context object?\", and implementation details leaking out all over the place. I'm just getting started with graph/prisma, but I'd really like to find a better way...","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":609}}141{"id":"stack-76734254","source":"stackoverflow","questionId":76734254,"title":"TypeError: Cannot read properties of undefined\" when inserting data with Prisma in Next.js","tags":["next.js","prisma"],"text":"Title: TypeError: Cannot read properties of undefined\" when inserting data with Prisma in Next.js\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to insert data into an \"actualite\" table using Prisma in my Next.js project. However, I'm encountering a \"TypeError: Cannot read properties of undefined (reading 'actualite')\" error when running the API.\n\nHere's my API code:\n\n```\n// api/actualites.js\n\nimport { prisma } from '@prisma/client';\n\nexport default async function handler(req, res) {\n if (req.method === 'POST') {\n const { titre, description } = req.body;\n\n try {\n const createdActualite = await prisma.actualite.create({\n data: {\n titre,\n description,\n },\n });\n\n res.status(200).json(createdActualite);\n } catch (error) {\n console.error(error);\n res.status(500).json({ error: 'An error occurred while publishing the news.' });\n }\n } else {\n res.status(405).json({ error: 'Method not allowed. Please use the POST method.' });\n }\n}\n```\n\nI'm confident that the request is being sent correctly with the required parameters, but I'm not sure why I'm still getting this error.\n\nI have verified that all Prisma dependencies are properly installed using the npm install @prisma/client prisma command, and I have also initialized Prisma correctly in my project.\n\n\r\n\r\n\n```\n// schema.prisma\n\ndatasource db {\n provider = \"sqlite\"\n url = \"file:./stable.db\"\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Actualite {\n id Int @id @default(autoincrement())\n titre String\n contenu String\n image String \n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\n========================================\n\nTop Answer:\nHave you updated your client package via\n\n```\nnpx prisma generate\n```\n\nevery time you change schema you should run that command in order to bring the latest changes from your prisma file to the client pacakge. Check out https://www.prisma.io/docs/reference/api-reference/command-reference#synopsis\n\n========================================\n\nCode:\n```text\n// api/actualites.js\n\nimport { prisma } from '@prisma/client';\n\nexport default async function handler(req, res) {\n  if (req.method === 'POST') {\n    const { titre, description } = req.body;\n\n    try {\n      const createdActualite = await prisma.actualite.create({\n        data: {\n          titre,\n          description,\n        },\n      });\n\n      res.status(200).json(createdActualite);\n    } catch (error) {\n      console.error(error);\n      res.status(500).json({ error: 'An error occurred while publishing the news.' });\n    }\n  } else {\n    res.status(405).json({ error: 'Method not allowed. Please use the POST method.' });\n  }\n}\n```\n\n```js\n// schema.prisma\n\ndatasource db {\n  provider = \"sqlite\"\n  url      = \"file:./stable.db\"\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Actualite {\n  id        Int     @id @default(autoincrement())\n  titre     String\n  contenu   String\n  image     String \n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n}\n```\n\n```js\nimport { PrismaClient } from '@prisma/client';\n    \n     const prisma = new PrismaClient();\n    \n     export default async function handler(req, res) {\n      // ... your code ...\n     }\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n     \n    const globalForPrisma = globalThis as unknown as {\n    \n      prisma: PrismaClient | undefined\n    \n    }\n     \n    export const prisma = globalForPrisma.prisma ?? new PrismaClient()\n    \n    if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma\n```\n\n```text\nnpx prisma generate\n```\n\n========================================\n\nComments:\n- yes it's already done\n- can you see `actualite` if you search in your prisma/client package?\n- Also did you initialize your prisma client? `const prisma = new PrismaClient({ log: ['query', 'info'] })`\n- The command that you are making reference is npx prisma generate\n- Thank you very much, I searched too far haha bless you","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":166,"estimatedTokens":987}}142{"id":"stack-69899392","source":"stackoverflow","questionId":69899392,"title":"How to resolve 'getUserByAccount is not a function' in next-auth?","tags":["next.js","prisma","next-auth"],"text":"Title: How to resolve 'getUserByAccount is not a function' in next-auth?\nTags: next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI've updated Nextjs to it's newest version and also updated next-auth and the prisma adapter as specified by the docs.\n\nHowever, when I try to authenticate in the app with `signIn` I get the following error with the latest updates:\n\n```\n[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] \nhttps://next-auth.js.org/errors#oauth_callback_handler_error getUserByAccount is not a function {\n message: 'getUserByAccount is not a function',\n stack: 'TypeError: getUserByAccount is not a function\\n' +\n ' at Object.callback (/home/.../node_modules/next-auth/core/routes/callback.js:81:39)\\n' +\n ' at runMicrotasks ()\\n' +\n ' at processTicksAndRejections (internal/process/task_queues.js:95:5)\\n' +\n ' at async NextAuthHandler (/home/.../node_modules/next-auth/core/index.js:103:28)\\n' +\n ' at async NextAuthNextHandler (/home/.../node_modules/next-auth/next/index.js:40:7)\\n' +\n ' at async [...]/node_modules/next-auth/next/index.js:80:32\\n' +\n ' at async Object.apiResolver (/home/.../node_modules/next/dist/server/api-utils.js:102:9)\\n' +\n ' at async DevServer.handleApiRequest (/home/.../node_modules/next/dist/server/next-server.js:1014:9)\\n' +\n ' at async Object.fn (/home/.../node_modules/next/dist/server/next-server.js:901:37)\\n' +\n ' at async Router.execute (/home/.../node_modules/next/dist/server/router.js:210:32)',\n name: 'TypeError'\n}\n```\n\nIs there something I'm doing wrong, or is there an incompatibility I'm missing?\n\nRelevant `package.json`:\n\n```\n...\n \"@next-auth/prisma-adapter\": \"^0.5.2-next.19\",\n \"next\": \"^12.0.3\",\n \"next-auth\": \"4.0.0-beta.6\",\n \"prisma\": \"^3.4.1\",\n...\n```\n\n`[...nextauth].ts`:\n\n```\nimport NextAuth from 'next-auth';\nimport CognitoProvider from 'next-auth/providers/cognito';\nimport { PrismaAdapter } from '@next-auth/prisma-adapter';\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nexport default NextAuth({\n adapter: PrismaAdapter(prisma),\n providers: [\n CognitoProvider({\n clientId: process.env.COGNITO_CLIENT_ID,\n clientSecret: process.env.COGNITO_CLIENT_SECRET,\n issuer: process.env.COGNITO_ISSUER,\n }),\n ],\n\n callbacks: {\n async session({ session, user }) {\n session.userId = user.id;\n session.role = user.role;\n return Promise.resolve(session);\n },\n },\n});\n```\n\n========================================\n\nTop Answer:\nIn the NextAuth.JS 4.0 the \"Prisma schema\" have slightly changed.\n\nFrom the upgrade guide:\n\n- `created_at`/`createdAt` and `updated_at`/`updatedAt` fields are removed from all Models.\n\n- `user_id`/`userId` consistently named `userId`.\n\n- `compound_id`/`compoundId` is removed from Account.\n\n- `access_token`/`accessToken` is removed from Session.\n\n- `email_verified`/`emailVerified` on User is consistently named `email_verified`.\n\n- `provider_id`/`providerId` renamed to provider on Account\n\n- `provider_type`/`providerType` renamed to type on Account\n\n- `provider_account_id`/`providerAccountId` on Account is consistently named `providerAccountId`\n\n- `access_token_expires`/`accessTokenExpires` on Account renamed to `expires_in`\n\n- New fields on Account: `expires_at`, `token_type`, `scope`, `id_token`, `session_state`\n\n- `verification_requests` table has been renamed to `verification_tokens`\n\nComplete new schema in:\nhttps://next-auth.js.org/adapters/prisma\n\n========================================\n\nCode:\n```text\n[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] \nhttps://next-auth.js.org/errors#oauth_callback_handler_error getUserByAccount is not a function {\n  message: 'getUserByAccount is not a function',\n  stack: 'TypeError: getUserByAccount is not a function\\n' +\n    '    at Object.callback (/home/.../node_modules/next-auth/core/routes/callback.js:81:39)\\n' +\n    '    at runMicrotasks (<anonymous>)\\n' +\n    '    at processTicksAndRejections (internal/process/task_queues.js:95:5)\\n' +\n    '    at async NextAuthHandler (/home/.../node_modules/next-auth/core/index.js:103:28)\\n' +\n    '    at async NextAuthNextHandler (/home/.../node_modules/next-auth/next/index.js:40:7)\\n' +\n    '    at async [...]/node_modules/next-auth/next/index.js:80:32\\n' +\n    '    at async Object.apiResolver (/home/.../node_modules/next/dist/server/api-utils.js:102:9)\\n' +\n    '    at async DevServer.handleApiRequest (/home/.../node_modules/next/dist/server/next-server.js:1014:9)\\n' +\n    '    at async Object.fn (/home/.../node_modules/next/dist/server/next-server.js:901:37)\\n' +\n    '    at async Router.execute (/home/.../node_modules/next/dist/server/router.js:210:32)',\n  name: 'TypeError'\n}\n```\n\n```text\n...\n    \"@next-auth/prisma-adapter\": \"^0.5.2-next.19\",\n    \"next\": \"^12.0.3\",\n    \"next-auth\": \"4.0.0-beta.6\",\n    \"prisma\": \"^3.4.1\",\n...\n```\n\n```text\nimport NextAuth from 'next-auth';\nimport CognitoProvider from 'next-auth/providers/cognito';\nimport { PrismaAdapter } from '@next-auth/prisma-adapter';\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nexport default NextAuth({\n  adapter: PrismaAdapter(prisma),\n  providers: [\n    CognitoProvider({\n      clientId: process.env.COGNITO_CLIENT_ID,\n      clientSecret: process.env.COGNITO_CLIENT_SECRET,\n      issuer: process.env.COGNITO_ISSUER,\n    }),\n  ],\n\n  callbacks: {\n    async session({ session, user }) {\n      session.userId = user.id;\n      session.role = user.role;\n      return Promise.resolve(session);\n    },\n  },\n});\n```\n\n```text\nsignIn\n```\n\n```text\npackage.json\n```\n\n```text\n[...nextauth].ts\n```\n\n```text\nnpm uninstall next-auth @next-auth/prisma-adapter\n```\n\n```text\nnpm install @next-auth/prisma-adapter\n```\n\n```text\ncreated_at\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdated_at\n```\n\n```text\nupdatedAt\n```\n\n```text\nuser_id\n```\n\n```text\nuserId\n```\n\n```text\nuserId\n```\n\n```text\ncompound_id\n```\n\n```text\ncompoundId\n```\n\n```text\naccess_token\n```\n\n```text\naccessToken\n```\n\n```text\nemail_verified\n```\n\n```text\nemailVerified\n```\n\n```text\nemail_verified\n```\n\n```text\nprovider_id\n```\n\n```text\nproviderId\n```\n\n```text\nprovider_type\n```\n\n```text\nproviderType\n```\n\n```text\nprovider_account_id\n```\n\n```text\nproviderAccountId\n```\n\n```text\nproviderAccountId\n```\n\n```text\naccess_token_expires\n```\n\n```text\naccessTokenExpires\n```\n\n```text\nexpires_in\n```\n\n```text\nexpires_at\n```\n\n```text\ntoken_type\n```\n\n```text\nscope\n```\n\n```text\nid_token\n```\n\n```text\nsession_state\n```\n\n```text\nverification_requests\n```\n\n```text\nverification_tokens\n```\n\n```bash\n$ npm uninstall next-auth @next-auth/prisma-adapter\n$ npm install @next-auth/prisma-adapter next-auth\n```\n\n```text\nnpx prisma db push\n```\n\n========================================\n\nComments:\n- Now it's npm install @auth/prisma-adapter\n- so, no need to install next-auth? what about the handler? how do you export it?\n- Yes, you need to make sure you get matching versions of these packages or issues will arise.","metadata":{"transformedAt":"2026-08-18T18:33:14.830Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":321,"estimatedTokens":1720}}143{"id":"stack-72096926","source":"stackoverflow","questionId":72096926,"title":"Return ENUM - Cannot return null for non-nullable field","tags":["apollo","apollo-server","prisma","graphql-codegen"],"text":"Title: Return ENUM - Cannot return null for non-nullable field\nTags: apollo, apollo-server, prisma, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI am using apollo-server-lambda, Prisma ORM and graphql-codegen.\n\nI have a query (`getBookById`) that returns a `Book`. `Book` contains an enum called `BookStatus`. I want to be able to return in ENUM in the playground but I get the error:\n\nCannot return null for non-nullable field Book.bookStatus.\n\n**BookStatus - TypeDef**\n\n```\nenum BookStatus {\n OPEN\n DRAFT\n CLOSED\n}\n```\n\n**Book - TypeDef**\n\n```\ntype Book {\n id: ID!\n title: String!\n bookStatus: BookStatus!\n}\n```\n\n**getBookById - TypeDef**\n\n```\ntype Query {\n getBookById(getBookByIdInput: GetBookByIdInput): Book\n}\n```\n\nhttps://i.sstatic.net/HI9dD.png\n\n========================================\n\nCode:\n```text\nenum BookStatus {\n  OPEN\n  DRAFT\n  CLOSED\n}\n```\n\n```text\ntype Book {\n  id: ID!\n  title: String!\n  bookStatus: BookStatus!\n}\n```\n\n```text\ntype Query {\n  getBookById(getBookByIdInput: GetBookByIdInput): Book\n}\n```\n\n```text\ngetBookById\n```\n\n```text\nBook\n```\n\n```text\nBook\n```\n\n```text\nBookStatus\n```\n\n```text\nconst foundBook = await prisma.book.findUnique({\n    where: {\n      id: bookId\n    }\n  });\n```\n\n```text\nconst newBook = await prisma.book.create({\n    data: {\n      user_id: userId,\n      title: title,\n      author: author,\n      publication_year: publicationYear,\n      isbn: isbn,\n      photos: photos,\n      book_condition: bookCondition,\n      exchange_yype: exchangeType,\n      book_status: bookStatus,\n    },\n  });\n      \n  return newBook;\n\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":109,"estimatedTokens":394}}144{"id":"stack-73693136","source":"stackoverflow","questionId":73693136,"title":"Prisma PostgreSQL queryRaw error code 42P01 table does not exist","tags":["sql","reactjs","postgresql","next.js","prisma"],"text":"Title: Prisma PostgreSQL queryRaw error code 42P01 table does not exist\nTags: sql, reactjs, postgresql, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to run a query that searches items in the Item table by how similar their title and description are to a value, the query is the following:\n\n```\nlet items = await prisma.$queryRaw`SELECT * FROM item WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`\n```\n\nHowever when the code is run I receive the following error:\n\n```\nerror - PrismaClientKnownRequestError: \nInvalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `42P01`. Message: `table \"item\" does not exist`\n code: 'P2010',\n clientVersion: '4.3.1',\n meta: { code: '42P01', message: 'table \"item\" does not exist' },\n page: '/api/marketplace/search'\n}\n```\n\nI have run also the following query:\n\n```\nlet tables = await prisma.$queryRaw`SELECT * FROM pg_catalog.pg_tables;`\n```\n\nWhich correctly shows that the Item table exists! Where is the error?\n\n========================================\n\nCode:\n```text\nlet items = await prisma.$queryRaw`SELECT * FROM item WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`\n```\n\n```text\nerror - PrismaClientKnownRequestError: \nInvalid `prisma.$queryRaw()` invocation:\n\n\nRaw query failed. Code: `42P01`. Message: `table \"item\" does not exist`\n  code: 'P2010',\n  clientVersion: '4.3.1',\n  meta: { code: '42P01', message: 'table \"item\" does not exist' },\n  page: '/api/marketplace/search'\n}\n```\n\n```text\nlet tables = await prisma.$queryRaw`SELECT * FROM pg_catalog.pg_tables;`\n```\n\n```text\nlet items = await prisma.$queryRaw`SELECT * FROM \"Item\" ... blah blah\n```\n\n========================================\n\nComments:\n- I'm not a PostgreSQL person but does the table name that you're querying have the same casing as what's in the db? For example, does the db say `Item` as opposed to `item`?\n- @drethedevjs I have tried both with `Item` and with `item`, still does not work...\n- I tried `Item` because in the database the table name is `Item`\n- Is this your first db query in your app? If not, are all the other queries of specific tables working?","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":545}}145{"id":"stack-77209892","source":"stackoverflow","questionId":77209892,"title":"Pass Prisma transaction into a function in typescript","tags":["typescript","transactions","prisma","typing"],"text":"Title: Pass Prisma transaction into a function in typescript\nTags: typescript, transactions, prisma, typing\nSource: Stack Overflow\n\nQuestion:\nHi I have following issue. I have prisma transaction but I would like to pass the prisma transaction client into a function like this:\n\n\r\n\r\n\n```\n...\nprisma.$transaction(async (tx) => {\n someFunction(tx)\n})\n...\n\nfunction someFunction(tx: WHATTOTYPEHERE){\n}\n```\n\n\r\n\r\n\r\n\nHowever I am doing it in typescript and I don't want to use type ANY. But i dont know how to type the interactive transactin prisma client... the \"WHATTOTYPEHERE\" type for it.\n\nAny help is appreciated\n\n========================================\n\nTop Answer:\nthis code is also work and this is the 1st way\n\n```\nimport { PrismaClient } from \"@prisma/client\";\n\nexport type PrismaTransactionalClient = Parameters[0]\n>[0];\n```\n\nbut there is a 2nd way and this is the official way\n\n```\nimport { Prisma } from \"@prisma/client\";\n\nexport type PrismaTransactionalClient = Prisma.TransactionClient;\n```\n\n========================================\n\nCode:\n```js\n...\nprisma.$transaction(async (tx) => {\n  someFunction(tx)\n})\n...\n\nfunction someFunction(tx: WHATTOTYPEHERE){\n}\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\";\n\nexport type PrismaTransactionalClient = Parameters<\n    Parameters<PrismaClient['$transaction']>[0]\n>[0];\n```\n\n```text\nParameters\n```\n\n```text\n$transaction\n```\n\n```text\n$transaction's\n```\n\n```text\n$transaction<R>(fn: (prisma: Omit<this, \"$connect\" | \"$disconnect\" | \"$on\" | \"$transaction\" | \"$use\">) => Promise<R>, options?: { maxWait?: number, timeout?: number }): Promise<R>\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\";\n\ntype PrismaTransactionClient = Omit<PrismaClient, \"$connect\" | \"$disconnect\" | \"$on\" | \"$transaction\" | \"$use\">\n\nfunction someFunction(tx: PrismaTransactionClient){\n// code here\n}\n```\n\n```text\n$transaction\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\";\n\nexport type PrismaTransactionalClient = Parameters<\n    Parameters<PrismaClient['$transaction']>[0]\n>[0];\n```\n\n```text\nimport { Prisma } from \"@prisma/client\";\n\nexport type PrismaTransactionalClient = Prisma.TransactionClient;\n```\n\n========================================\n\nComments:\n- Are you missing the $transaction type in your new declared Type? this worked for me: `Parameters[0]>[0]`\n- @andy That is essentially the same thing. In your situation `prisma` refers to the instance, but in my answer `PrismaClient` refers to the class.\n- idk, what @andy has there works for me, but the class-based one doesn't.","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":121,"estimatedTokens":637}}146{"id":"stack-70682378","source":"stackoverflow","questionId":70682378,"title":"how to create a optional list field in prisma","tags":["javascript","node.js","postgresql","prisma"],"text":"Title: how to create a optional list field in prisma\nTags: javascript, node.js, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am creating a basic crud api with nodejs and prisma. My Schema is as follows:\n\n\r\n\r\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n shadowDatabaseUrl = env(\"SHADOW_DATABASE_URL\")\n}\n\n \n\nmodel Category {\n id String @unique @default(cuid())\n title String\n description String\n products Product[]\n}\n\nmodel Product {\n id String @unique @default(cuid())\n title String\n description String\n price Float\n createdAt DateTime @default(now())\n updatedAt DateTime?\n\n category Category? @relation(fields: [categoryId], references: [id])\n categoryId String?\n}\n```\n\n\r\n\r\n\r\n\nI am trying to make the products field in the Category model optional. But Prisma doesn't allow that. But I want my users to create a category even without creating a post or vice-versa. How can I get around this?\n\n========================================\n\nCode:\n```js\ngenerator client {\n       provider = \"prisma-client-js\"\n}\n\ndatasource db {\n       provider          = \"postgresql\"\n       url               = env(\"DATABASE_URL\")\n       shadowDatabaseUrl = env(\"SHADOW_DATABASE_URL\")\n}\n\n  \n\nmodel Category {\n       id          String    @unique @default(cuid())\n       title       String\n       description String\n       products    Product[]\n}\n\nmodel Product {\n  id          String    @unique @default(cuid())\n  title       String\n  description String\n  price       Float\n  createdAt   DateTime  @default(now())\n  updatedAt   DateTime?\n\n  category   Category? @relation(fields: [categoryId],  references: [id])\n  categoryId String?\n}\n```\n\n```js\nawait prisma.category.create({\n  data: {\n    title: 'books',\n    description: 'books',\n    products: {},\n  }\n})\n```\n\n```js\nawait prisma.category.update({\n  where: {\n    id: \"category-id\"\n  },\n  data: {\n    products: {\n      connect: {\n        id: \"product-id\"\n      }\n    }\n  }\n})\n```\n\n```text\nproducts\n```\n\n```text\nCategory\n```\n\n========================================\n\nComments:\n- Thank you for your afford. But when I am making a post request for the category. I am given a json response of `products is not defined.\" even if I pass a empty products: [] array. I am not sure why this is happening\n- Thanks a lot man. The problem is solved\n- @AsiefMahir did you solve like Gergely suggested or what did you do?\n- If you're using the generated `CategoryModel` to validate your post request 's body parameter, you can use typescript `Pick` utility type to exclude the array prop. Ex: `Pick`\n- WHen you thought prisma couldn't be more retarded...","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":126,"estimatedTokens":666}}147{"id":"stack-69427050","source":"stackoverflow","questionId":69427050,"title":"How to extend globalThis/global type?","tags":["typescript","global","prisma"],"text":"Title: How to extend globalThis/global type?\nTags: typescript, global, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm working on a typescript project with Prisma and I saw this code on this guide that is using typescript. However my linter gives me errors for the following code.\n\n```\nimport { PrismaClient } from '@prisma/client';\n\nlet prisma: PrismaClient;\n\nif (process.env.NODE_ENV === 'production') {\n prisma = new PrismaClient();\n} else {\n if (!global.prisma) {\n global.prisma = new PrismaClient();\n }\n prisma = global.prisma;\n}\n\nexport default prisma;\n```\n\nThe error message for lines 8,9,11 (for `global.prisma`) is the following\n\nElement implicitly has an 'any' type because type 'typeof globalThis' has no index signature. ts(7017)\n\nHow can I extend the type of globalThis or global with `Prismaclient` so that it works as intended?\n\n========================================\n\nCode:\n```js\nimport { PrismaClient } from '@prisma/client';\n\nlet prisma: PrismaClient;\n\nif (process.env.NODE_ENV === 'production') {\n  prisma = new PrismaClient();\n} else {\n  if (!global.prisma) {\n    global.prisma = new PrismaClient();\n  }\n  prisma = global.prisma;\n}\n\nexport default prisma;\n```\n\n```text\nglobal.prisma\n```\n\n```text\nPrismaclient\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n\ndeclare global {\n  var prisma: PrismaClient | undefined\n}\n\nexport const prisma =\n  global.prisma ||\n  new PrismaClient()\n\nif (process.env.NODE_ENV !== 'production') global.prisma = prisma\n```\n\n```js\nif (process.env.NODE_ENV === 'production') {\n  prisma = new PrismaClient();\n} else {\n  if (!(global as any).prisma) {\n    (global as any).prisma = new PrismaClient();\n  }\n  prisma = (global as any).prisma;\n}\n```\n\n```text\nglobal\n```\n\n```text\nany\n```\n\n========================================\n\nComments:\n- Learn and use the singleton pattern so you don't have to hack it like this.\n- @AliHabibzadeh Could you give an example of how you would solve this?\n- Thanks for posting this question! Was facing the exact same issue a year later and it was causing me tons of headaches.\n- Alternative solution though hacky, is good workaround","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":98,"estimatedTokens":529}}148{"id":"stack-72111295","source":"stackoverflow","questionId":72111295,"title":"Prisma, update scalarList/array","tags":["javascript","typescript","postgresql","next.js","prisma"],"text":"Title: Prisma, update scalarList/array\nTags: javascript, typescript, postgresql, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI´m doing an Spotify clone and I´m trying to add a song to a playlist but my query doesn't work, until this point, everything was good following the documentation on prisma docs, but I cannot do this query, every time get an error, so if someone can tell me, how can I do this with an example, I'll be very grateful.\n\nMy question is, having this schema, how can I add a song to a playlist? there are two models affected by the query, song (where i am trying to add) and playlist.\n\nMy schema:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n shadowDatabaseUrl = env(\"SHADOW_DATABASE_URL\")\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n email String @unique\n firstName String\n lastName String\n password String\n playlists Playlist[]\n}\n\n// here\nmodel Song {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n name String\n artist Artist @relation(fields: [artistId], references: [id])\n artistId Int\n playlists Playlist[]\n duration Int\n url String\n}\n\nmodel Artist {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n songs Song[]\n name String @unique\n}\n\n// here\nmodel Playlist {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n name String\n songs Song[]\n user User @relation(fields: [userId], references: [id])\n userId Int\n}\n```\n\nI am trying to add the song like this:\n\n```\nlet songId = 1;\nlet playlistId = 1;\nlet lists;\n\n// get the playlists the song is part of\n\nlists = await prisma.song.findFirst({\n select: {\n playlists: true\n },\n where: {\n id: +songId\n }\n })\n\n// get the playlist data i need\nconst list = await prisma.playlist.findUnique({\n where: {\n id: playlistId\n }\n })\n\n// create the array for update with the data\n// plus the data I want to add\n\nlists = [ ...lists.playlists, list ]\n\n// trying to update the old array with the new data (lists)\n// this is what i'm doing wrong, help please\n\nawait prisma.song.update({\n where: { id: +songId },\n data:{\n playlists: lists\n\n }\n })\n```\n\n========================================\n\nTop Answer:\nI find a solution :\n\nhttps://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#add-new-related-records-to-an-existing-record\n\n```\nawait prisma.song.update({\n where: { id: +songId },\n data:{\n playlists:{\n create:{\n data:{ id: playlistId}\n }\n } \n }\n})\n```\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n  shadowDatabaseUrl = env(\"SHADOW_DATABASE_URL\")\n}\n\nmodel User {\n  id        Int       @id @default(autoincrement())\n  createdAt DateTime  @default(now())\n  updatedAt DateTime  @updatedAt\n  email     String    @unique\n  firstName String\n  lastName  String\n  password  String\n  playlists Playlist[]\n}\n\n// here\nmodel Song {\n  id        Int       @id @default(autoincrement())\n  createdAt DateTime  @default(now())\n  updatedAt DateTime  @updatedAt\n  name      String\n  artist    Artist    @relation(fields: [artistId], references: [id])\n  artistId  Int\n  playlists Playlist[]\n  duration  Int\n  url       String\n}\n\nmodel Artist {\n  id        Int       @id @default(autoincrement())\n  createdAt DateTime  @default(now())\n  updatedAt DateTime  @updatedAt\n  songs     Song[]\n  name      String    @unique\n}\n\n// here\nmodel Playlist {\n  id        Int       @id @default(autoincrement())\n  createdAt DateTime  @default(now())\n  updatedAt DateTime  @updatedAt\n  name      String\n  songs     Song[]\n  user      User      @relation(fields: [userId], references: [id])\n  userId    Int\n}\n```\n\n```text\nlet songId = 1;\nlet playlistId = 1;\nlet lists;\n\n// get the playlists the song is part of\n\nlists = await prisma.song.findFirst({\n        select: {\n            playlists: true\n        },\n        where: {\n            id: +songId\n        }\n    })\n\n// get the playlist data i need\nconst list = await prisma.playlist.findUnique({\n       where: {\n            id: playlistId\n         }\n       })\n\n// create the array for update with the data\n// plus the data I want to add\n\nlists = [ ...lists.playlists, list ]\n\n// trying to update the old array with the new data (lists)\n// this is what i'm doing wrong, help please\n\nawait prisma.song.update({\n     where: { id: +songId },\n     data:{\n         playlists: lists\n\n        }\n     })\n```\n\n```text\nconst song = await prisma.song.findUnique({\n    select: {\n       playlists: true\n     },\n     where: {\n        id: +songId\n     }\n})\n\n//   get an array of objects, id: playlistId\nconst songPlaylistsIds = song.playlists.map( playlist => ({id: playlist.id}))\n\n//   I prepare the array with the content that already exists plus the new content that I want to add:\nconst playlists =  [...songPlaylistsIds, { id: playlistId}]\n\nawait prisma.song.update({\n       where: { id: +songId },\n       data:{\n          playlists: {\n             // finally for each object in the array i get, id: playlistId and it works.\n             set: playlists.map( playlistSong => ({ ...playlistSong })) \n          }                \n       }\n})\n```\n\n```text\nawait prisma.song.update({\n       where: { id: +songId },\n       data:{\n          playlists:{\n              create:{\n                 data:{ id: playlistId}\n              }\n          }                \n       }\n})\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":270,"estimatedTokens":1488}}149{"id":"stack-75197409","source":"stackoverflow","questionId":75197409,"title":"Prisma warn 10 instances","tags":["reactjs","next.js","prisma"],"text":"Title: Prisma warn 10 instances\nTags: reactjs, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm getting the following warning in the console:\n\n```\nwarn(prisma-client) There are already 10 instances of Prisma Client actively running.\n```\n\nI've tried to the prisma documentantion to solve this warning, explained here: https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#prismaclient-in-long-running-applications\n\nSo I've created a file with the following code:\n\n```\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\nexport default prisma\n```\n\nAnd then import prisma in the api like this:\n\n```\nimport prisma from \"@/backend/db\"\n```\n\nBut the warning persists.\n\nThanks in advance!\n\n========================================\n\nCode:\n```text\nwarn(prisma-client) There are already 10 instances of Prisma Client actively running.\n```\n\n```text\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\nexport default prisma\n```\n\n```text\nimport prisma from \"@/backend/db\"\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n\nconst globalForPrisma = global as unknown as { prisma: PrismaClient }\n\nexport const prisma =\n  globalForPrisma.prisma ||\n  new PrismaClient({\n    log: ['query'],\n  })\n\nif (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":61,"estimatedTokens":341}}150{"id":"stack-62869666","source":"stackoverflow","questionId":62869666,"title":"Prisma 2: Unknown arg `where` in select.count.where for type undefined","tags":["prisma","prisma2"],"text":"Title: Prisma 2: Unknown arg `where` in select.count.where for type undefined\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm unable to apply a where clause to a simple count() query on a model. If I remove the where clause it works just fine and returns the number of rows in that table.\n\nGood:\n`let result = await prisma.articles.count()`\n\nBad:\n`let result = await prisma.articles.count({ where: { article_id: 1 } })`\n\nError:\n\n```\nUnknown arg `where` in select.count.where for type undefined. Did you mean `select`? Available args:\ntype count {\n\n}\n```\n\nIt doesn't matter which column in the schema I use, same error. How do I troubleshoot this?\n\n========================================\n\nCode:\n```text\nUnknown arg `where` in select.count.where for type undefined. Did you mean `select`? Available args:\ntype count {\n\n}\n```\n\n```text\nlet result = await prisma.articles.count()\n```\n\n```text\nlet result = await prisma.articles.count({ where: { article_id: 1 } })\n```\n\n```text\n@prisma/cli\n```\n\n```text\n@prisma/client\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n2.2.0\n```\n\n========================================\n\nComments:\n- Bingo - the versions were slightly off. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":62,"estimatedTokens":296}}151{"id":"stack-69568781","source":"stackoverflow","questionId":69568781,"title":"How to create a custom health check for Prisma with @nestjs/terminus?","tags":["nestjs","prisma","health-check"],"text":"Title: How to create a custom health check for Prisma with @nestjs/terminus?\nTags: nestjs, prisma, health-check\nSource: Stack Overflow\n\nQuestion:\nSince @nestjs/terminus doesn't provide a health check for Prisma, I'm trying to create it based on their Mongoose health check.\n\nWhen I try:\n\n```\nimport * as Prisma from 'prisma';\n...\n...\n private getContextConnection(): any | null {\n const {\n getConnectionToken,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n } = require('prisma') as typeof Prisma;\n\n try {\n return this.moduleRef.get(getConnectionToken('DatabaseConnection') as string, {\n strict: false,\n });\n } catch (err) {\n return null;\n }\n }\n...\n...\n const connection = options.connection || this.getContextConnection();\n\n if (!connection) {\n throw new ConnectionNotFoundError(\n this.getStatus(key, isHealthy, {\n message: 'Connection provider not found in application context',\n }),\n );\n }\n```\n\nI always seem to get: \"message\": \"Connection provider not found in application context\".\nThere is a problem with the connection or I don't really understand how the health check actually works\n\n========================================\n\nTop Answer:\nThis question helped me build a Prisma health check for NestJS.\n\nHere's what I made:\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { HealthCheckError, HealthIndicator, HealthIndicatorResult } from \"@nestjs/terminus\";\nimport { PrismaService } from \"./prisma.service\";\n\n@Injectable()\nexport class PrismaHealthIndicator extends HealthIndicator {\n constructor(private readonly prismaService: PrismaService) {\n super();\n }\n\n async isHealthy(key: string): Promise {\n try {\n await this.prismaService.$queryRaw`SELECT 1`;\n return this.getStatus(key, true);\n } catch (e) {\n throw new HealthCheckError(\"Prisma check failed\", e);\n }\n }\n}\n```\n\nThis injects a `PrismaService` exactly as it is shown in the NestJS docs. https://docs.nestjs.com/recipes/prisma#use-prisma-client-in-your-nestjs-services\n\nYou could alternatively replace `prismaService` with `new PrismaClient()`.\n\n========================================\n\nCode:\n```text\nimport * as Prisma from 'prisma';\n...\n...\n  private getContextConnection(): any | null {\n    const {\n      getConnectionToken,\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n    } = require('prisma') as typeof Prisma;\n\n    try {\n      return this.moduleRef.get(getConnectionToken('DatabaseConnection') as string, {\n        strict: false,\n      });\n    } catch (err) {\n      return null;\n    }\n  }\n...\n...\n    const connection = options.connection || this.getContextConnection();\n\n    if (!connection) {\n      throw new ConnectionNotFoundError(\n        this.getStatus(key, isHealthy, {\n          message: 'Connection provider not found in application context',\n        }),\n      );\n    }\n```\n\n```js\nprisma.$queryRaw`SELECT 1`\n```\n\n```text\nNestJSMongoose\n```\n\n```text\nPrisma\n```\n\n```text\ngetConnectionToken\n```\n\n```text\nPrisma\n```\n\n```text\nterminus\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\nimport { HealthCheckError, HealthIndicator, HealthIndicatorResult } from \"@nestjs/terminus\";\nimport { PrismaService } from \"./prisma.service\";\n\n@Injectable()\nexport class PrismaHealthIndicator extends HealthIndicator {\n  constructor(private readonly prismaService: PrismaService) {\n    super();\n  }\n\n  async isHealthy(key: string): Promise<HealthIndicatorResult> {\n    try {\n      await this.prismaService.$queryRaw`SELECT 1`;\n      return this.getStatus(key, true);\n    } catch (e) {\n      throw new HealthCheckError(\"Prisma check failed\", e);\n    }\n  }\n}\n```\n\n```text\nPrismaService\n```\n\n```text\nprismaService\n```\n\n```text\nnew PrismaClient()\n```\n\n```js\n// keep in mind that it is not recommended to send server errors directly to the client,\n// you may not want to expose your DB location or other sensitive data\nLogger.error(error, `${PrismaHealthIndicator.name}::isHealthy`)\n\nthrow new HealthCheckError(\n  'cannot perform DB checks',\n  this.getStatus(key, false, {\n    message: 'cannot perform DB checks'\n  })\n)\n```\n\n========================================\n\nComments:\n- Since there's no NestJS Prisma package and therefore nobody registers the `DatabaseConnection` token, it probably makes more sense to do `PrismaClient.$connect()` in the health check.\n- Could you please add an example of how you'd use `PrismaHealthIndicator` in a health check controller","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":186,"estimatedTokens":1095}}152{"id":"stack-63079230","source":"stackoverflow","questionId":63079230,"title":"prisma2 set length and column type in prisma schema","tags":["prisma","prisma-graphql","prisma2"],"text":"Title: prisma2 set length and column type in prisma schema\nTags: prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nhow can i set string(varchar) length for string type be 50 and define a column be TEXT in prisma schema, for user table i want `name` be varchar(50) and `bio` be Text column.\nim creating my tables by prisma migrate save and up.\n\n```\nmodel User {\n\n id Int @default(autoincrement()) @id\n email String @unique\n password String\n name String ***** varchar 50****\n bio String *****TEXT ??\n\n}\n```\n\n========================================\n\nTop Answer:\n@Griffin is correct. Additionally, your `bio` field can be left as is. Prisma sets `String` type as native database `text` types by default (only PostgreSQL & SQLite only). You can also set it explicitly regardless of the database:\n\n```\nmodel User {\n id Int @default(autoincrement()) @id\n email String @unique\n password String\n name String @db.VarChar(50)\n bio String @db.Text\n}\n```\n\n========================================\n\nCode:\n```text\nmodel User {\n\n  id        Int      @default(autoincrement()) @id\n  email     String   @unique\n  password  String\n  name      String   ***** varchar 50****\n  bio       String  *****TEXT ??\n\n}\n```\n\n```text\nname\n```\n\n```text\nbio\n```\n\n```text\nmodel User {\n  id        Int      @default(autoincrement()) @id\n  email     String   @unique\n  password  String\n  name      String   @db.VarChar(50)\n}\n```\n\n```text\n@db.\n```\n\n```text\nvarchar\n```\n\n```text\nmodel User {\n  id        Int      @default(autoincrement()) @id\n  email     String   @unique\n  password  String\n  name      String   @db.VarChar(50)\n  bio       String   @db.Text\n}\n```\n\n```text\nbio\n```\n\n```text\nString\n```\n\n```text\ntext\n```\n\n========================================\n\nComments:\n- Thanks. Unfortunately, Sqlite only supports `TEXT`. prisma.io/docs/reference/api-reference/&hellip;\n- Unfortunately, Sqlite only supports `TEXT`. prisma.io/docs/reference/api-reference/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":102,"estimatedTokens":487}}153{"id":"stack-68415224","source":"stackoverflow","questionId":68415224,"title":"prisma any good if i need mysql view and stored procedures in nextJS","tags":["next.js","prisma"],"text":"Title: prisma any good if i need mysql view and stored procedures in nextJS\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm starting to learn prisma to replace my nodejs back-end in my nextJS app.\n\nIt seems that prisma is not made to work with views and stored procedures created in my mysql database.\n\nIs there even a point in switching to prisma if I cannot just use views and stored procedures, which allows me to create a user in the database that can only access those two and nothing else.\n\nany prisma pro's that could give confirm or deny what I am thinking\n\nThx\n\n========================================\n\nCode:\n```js\nconst rawSQL = `call foobar`;\n  const result = await prisma.$executeRaw(rawSQL);\n```\n\n```text\n$executeRaw\n```\n\n```text\n$queryRaw\n```\n\n```text\nfoobar\n```\n\n```text\n$executeRaw\n```\n\n```text\n$executeRaw\n```\n\n```text\n$queryRaw\n```\n\n========================================\n\nComments:\n- related if you are using typescript stackoverflow.com/questions/69564787/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":51,"estimatedTokens":250}}154{"id":"stack-71729285","source":"stackoverflow","questionId":71729285,"title":"Add constraint on combination of multiple fields of prisma model","tags":["prisma"],"text":"Title: Add constraint on combination of multiple fields of prisma model\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI have this model in Prisma:\n\n```\nmodel RegisteredPage {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n domain String // instagram, youtube,...\n page String // s4eed, dive, makeappwithme,...\n}\n```\n\nI want to add a constraint on the `domain` and `page` so that combination of them is unique. Should I make the combination of them as `ID`?\n\n========================================\n\nCode:\n```text\nmodel RegisteredPage {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  domain String // instagram, youtube,...\n  page   String // s4eed, dive, makeappwithme,...\n}\n```\n\n```text\ndomain\n```\n\n```text\npage\n```\n\n```text\nID\n```\n\n```text\nmodel RegisteredPage {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n\n  domain String // instagram, youtube,...\n  page   String // s4eed, dive, makeappwithme,...\n\n  @@unique([domain, page])\n}\n```\n\n```text\n@@unique\n```\n\n```text\n@@unique\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":66,"estimatedTokens":298}}155{"id":"stack-55216051","source":"stackoverflow","questionId":55216051,"title":"Define required or not for array fields in the prisma datamodel","tags":["prisma","prisma-graphql"],"text":"Title: Define required or not for array fields in the prisma datamodel\nTags: prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nWhat are the differences of followings. when to use a one over the other?\n\n```\nzones: [Zone]\nzones: [Zone!]\nzones: [Zone]!\nzones: [Zone!]!\n```\n\n========================================\n\nCode:\n```text\nzones: [Zone]\nzones: [Zone!]\nzones: [Zone]!\nzones: [Zone!]!\n```\n\n```text\nvalues         | [Zone] | [Zone!] | [Zone]! | [Zone!]! |\n--------------------------------------------------------\nnull           |    ✔   |    ✔    |    X    |     X    |\n[]             |    ✔   |    ✔    |    ✔    |     ✔    |\n[null]         |    ✔   |    X    |    ✔    |     X    |\n[\"a\",\"b\"]      |    ✔   |    ✔    |    ✔    |     ✔    |\n[\"a\",null,\"c\"] |    ✔   |    X    |    ✔    |     X    |\n```\n\n```text\n[Zone!]!\n```\n\n========================================\n\nComments:\n- Perfect!... also the answer is nicely organized.\n- what if I want to avoid [ ]? how is [ ] different from [null]? thanks\n- In a GraphQL shema, you cannot specify the required length, which means you cannot avoid an empty array ([]).\n- The difference between [] and [null] is that [] is an empty array, while [null] is an array with one element which is null. It's the same difference that can be seen in most languages.","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":45,"estimatedTokens":327}}156{"id":"stack-75192005","source":"stackoverflow","questionId":75192005,"title":"Prisma CreateMany with Connect","tags":["node.js","prisma"],"text":"Title: Prisma CreateMany with Connect\nTags: node.js, prisma\nSource: Stack Overflow\n\nQuestion:\nin Prisma is there a way to createMany with a connect?\n\nBasically this a million times:\n\nI read the documentation and there doesn't seem to be \"nested createMany\" but i think that's not that im doing (FWIW my code below wasn't able to be found in documentation either...)\n\n```\nconst result = await prisma.posts.create({\n data: {\n user: {\n connect: {\n id: user.id,\n },\n },\n ...postData,\n },\n });\n```\n\n========================================\n\nTop Answer:\nThis better works on my end. https://www.prisma.io/docs/orm/reference/prisma-client-reference#create\n\n```\nasync function main() {\n let users: Prisma.UserCreateInput[] = [\n {\n email: 'ariana@prisma.io',\n userId: { connect: { id }\n\n },\n {\n email: 'elsa@prisma.io',\n userId: { connect: { id }\n },\n ]\n\n await Promise.all(\n users.map(async (user) => {\n await prisma.user.create({\n data: user,\n })\n })\n )\n}\n```\n\n========================================\n\nCode:\n```js\nconst result = await prisma.posts.create({\n      data: {\n        user: {\n          connect: {\n            id: user.id,\n          },\n        },\n        ...postData,\n      },\n    });\n```\n\n```text\nconst result = await prisma.posts.createMany([\n      {\n        ...postData,\n       userId,\n      },\n    ]);\n```\n\n```js\nasync function main() {\n  let users: Prisma.UserCreateInput[] = [\n    {\n      email: 'ariana@prisma.io',\n      userId: { connect: { id }\n\n    },\n    {\n      email: 'elsa@prisma.io',\n      userId: { connect: { id }\n    },\n  ]\n\n  await Promise.all(\n    users.map(async (user) => {\n      await prisma.user.create({\n        data: user,\n      })\n    })\n  )\n}\n```\n\n========================================\n\nComments:\n- Not a good solution. What if you have 1.000.000 users? This would result in one million DB queries.","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":106,"estimatedTokens":459}}157{"id":"stack-74017747","source":"stackoverflow","questionId":74017747,"title":"How to use LIKE in Prisma ORM on number fields?","tags":["node.js","orm","prisma"],"text":"Title: How to use LIKE in Prisma ORM on number fields?\nTags: node.js, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nHaving some experience in writing raw SQL queries, I want to use Prisma in Node.js to ask Postgresql for something like that:\n\n```\nSELECT ..... WHERE dateField LIKE '2020-05%'\n```\n\nor\n\n```\nSELECT ..... WHERE numberField LIKE '%99'\n```\n\nI know, that the database will return what I want.\n\nI just can't make Prisma do that. Is it possible?\n\nFor string/varchar fields I use contains the keyword in where object and it works fine.\n\n```\nconst orders = await prisma.product.findMany({\n where: {\n textField: {\n contains: 'potato'\n }\n }\n});\n```\n\nIs there any workaround to get such functionality for date/number type fields?\n\n========================================\n\nCode:\n```query\nSELECT ..... WHERE dateField LIKE '2020-05%'\n```\n\n```query\nSELECT ..... WHERE numberField LIKE '%99'\n```\n\n```js\nconst orders = await prisma.product.findMany({\n  where: {\n    textField: {\n        contains: 'potato'\n    }\n  }\n});\n```\n\n```text\nLIKE\n```\n\n========================================\n\nComments:\n- This question seems to be an almost identical copy of this SO question ...\n- Thank you for taking the time to do this","metadata":{"transformedAt":"2026-08-18T18:33:14.831Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":65,"estimatedTokens":304}}158{"id":"stack-61449315","source":"stackoverflow","questionId":61449315,"title":"Input Object type XXX must define one or more fields in prisma 2.0","tags":["prisma","prisma-graphql","nexus-prisma"],"text":"Title: Input Object type XXX must define one or more fields in prisma 2.0\nTags: prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nI have the following `schema.prisma` file:\n\n```\nmodel Account {\n id Int @default(autoincrement()) @id\n name String\n transactions Transaction[]\n}\n\nmodel Transaction {\n id Int @default(autoincrement()) @id\n accountId Int\n account Account @relation(fields: [accountId], references: [id])\n}\n```\n\nI can execute\n\n```\nnpx prisma migrate save --experimental\nnpx prisma migrate up --experimental --verbose\nnpx prisma generate\n```\n\nwithout errors and database looks ok (this screenshot contains also currency but it does not have influence on this problem).\n\nhttps://i.sstatic.net/E3gkD.png\n\nBut when I execute `ApolloServer` that is using `nexusPrismaPlugin` I have error:\n\n```\nUsing ts-node version 8.9.0, typescript version 3.8.3\nError: Input Object type TransactionCreateWithoutAccountInput must define one or more fields.\n at assertValidSchema (/home/daniel/pro/cash/core/node_modules/graphql/type/validate.js:71:11)\n at assertValidExecutionArguments (/home/daniel/pro/cash/core/node_modules/graphql/execution/execute.js:136:35)\n at executeImpl (/home/daniel/pro/cash/core/node_modules/graphql/execution/execute.js:86:3)\n at Object.execute (/home/daniel/pro/cash/core/node_modules/graphql/execution/execute.js:64:63)\n at Object.generateSchemaHash (/home/daniel/pro/cash/core/node_modules/apollo-server-core/src/utils/schemaHash.ts:11:18)\n at ApolloServer.generateSchemaDerivedData (/home/daniel/pro/cash/core/node_modules/apollo-server-core/src/ApolloServer.ts:541:24)\n at new ApolloServerBase (/home/daniel/pro/cash/core/node_modules/apollo-server-core/src/ApolloServer.ts:400:32)\n at new ApolloServer (/home/daniel/pro/cash/core/node_modules/apollo-server-express/src/ApolloServer.ts:88:5)\n at new ApolloServer (/home/daniel/pro/cash/core/node_modules/apollo-server/src/index.ts:36:5)\n at Object. (/home/daniel/pro/cash/core/src/server.ts:5:1)\n[ERROR] 01:01:32 Error: Input Object type TransactionCreateWithoutAccountInput must define one or more fields.\n```\n\nMy code does contains nothing connected with Transaction. If I remove `Transaction` everything works great.\n\nIn generated code I can see in file:\n\n node_modules/@prisma/client/index.d.ts\n\n```\nexport type TransactionCreateWithoutAccountInput = {\n\n}\n\n...\n\nexport type TransactionCreateManyWithoutAccountInput = {\n create?: Enumerable | null\n connect?: Enumerable | null\n}\n\n...\n\nexport type TransactionUpdateManyWithoutAccountInput = {\n create?: Enumerable | null\n connect?: Enumerable | null\n set?: Enumerable | null\n disconnect?: Enumerable | null\n delete?: Enumerable | null\n update?: Enumerable | null\n updateMany?: Enumerable | null\n deleteMany?: Enumerable | null\n}\n```\n\nHow to fix it?\n\n========================================\n\nTop Answer:\nI have setup the same `schema.prisma` that you have above and I have created two types using `Nexus` in the following manner\n\n```\nimport { objectType } from '@nexus/schema'\n\nexport const Account = objectType({\n name: 'Account',\n definition(t) {\n t.model.id()\n t.model.name()\n t.model.transactions({\n pagination: true,\n })\n },\n})\n\nexport const Transaction = objectType({\n name: 'Transaction',\n definition(t) {\n t.model.id()\n t.model.account()\n },\n})\n```\n\nI have started the server and currently it's running properly. Have you added any other queries/mutations apart from this?\n\n========================================\n\nCode:\n```text\nmodel Account {\n  id Int @default(autoincrement()) @id\n  name String\n  transactions Transaction[]\n}\n\nmodel Transaction {\n  id Int @default(autoincrement()) @id\n  accountId Int\n  account Account @relation(fields: [accountId], references: [id])\n}\n```\n\n```text\nnpx prisma migrate save --experimental\nnpx prisma migrate up --experimental --verbose\nnpx prisma generate\n```\n\n```text\nUsing ts-node version 8.9.0, typescript version 3.8.3\nError: Input Object type TransactionCreateWithoutAccountInput must define one or more fields.\n    at assertValidSchema (/home/daniel/pro/cash/core/node_modules/graphql/type/validate.js:71:11)\n    at assertValidExecutionArguments (/home/daniel/pro/cash/core/node_modules/graphql/execution/execute.js:136:35)\n    at executeImpl (/home/daniel/pro/cash/core/node_modules/graphql/execution/execute.js:86:3)\n    at Object.execute (/home/daniel/pro/cash/core/node_modules/graphql/execution/execute.js:64:63)\n    at Object.generateSchemaHash (/home/daniel/pro/cash/core/node_modules/apollo-server-core/src/utils/schemaHash.ts:11:18)\n    at ApolloServer.generateSchemaDerivedData (/home/daniel/pro/cash/core/node_modules/apollo-server-core/src/ApolloServer.ts:541:24)\n    at new ApolloServerBase (/home/daniel/pro/cash/core/node_modules/apollo-server-core/src/ApolloServer.ts:400:32)\n    at new ApolloServer (/home/daniel/pro/cash/core/node_modules/apollo-server-express/src/ApolloServer.ts:88:5)\n    at new ApolloServer (/home/daniel/pro/cash/core/node_modules/apollo-server/src/index.ts:36:5)\n    at Object.<anonymous> (/home/daniel/pro/cash/core/src/server.ts:5:1)\n[ERROR] 01:01:32 Error: Input Object type TransactionCreateWithoutAccountInput must define one or more fields.\n```\n\n```text\nexport type TransactionCreateWithoutAccountInput = {\n\n}\n\n...\n\nexport type TransactionCreateManyWithoutAccountInput = {\n  create?: Enumerable<TransactionCreateWithoutAccountInput> | null\n  connect?: Enumerable<TransactionWhereUniqueInput> | null\n}\n\n...\n\nexport type TransactionUpdateManyWithoutAccountInput = {\n  create?: Enumerable<TransactionCreateWithoutAccountInput> | null\n  connect?: Enumerable<TransactionWhereUniqueInput> | null\n  set?: Enumerable<TransactionWhereUniqueInput> | null\n  disconnect?: Enumerable<TransactionWhereUniqueInput> | null\n  delete?: Enumerable<TransactionWhereUniqueInput> | null\n  update?: Enumerable<TransactionUpdateWithWhereUniqueWithoutAccountInput> | null\n  updateMany?: Enumerable<TransactionUpdateManyWithWhereNestedInput> | null\n  deleteMany?: Enumerable<TransactionScalarWhereInput> | null\n}\n```\n\n```text\nschema.prisma\n```\n\n```text\nApolloServer\n```\n\n```text\nnexusPrismaPlugin\n```\n\n```text\nTransaction\n```\n\n```text\nmodel Applications {\n  id          Int  @id @default(autoincrement())\n  applyingFor Job  @relation(fields: [jobId], references: [id])\n  jobId       Int\n  applicant   Profile @relation(fields: [applicantId], references: [id])\n  applicantId Int \n}`\n```\n\n```text\ndummy String?\n```\n\n```text\ntypegraphql-prisma\n```\n\n```text\nimport { objectType } from '@nexus/schema'\n\nexport const Account = objectType({\n  name: 'Account',\n  definition(t) {\n    t.model.id()\n    t.model.name()\n    t.model.transactions({\n      pagination: true,\n    })\n  },\n})\n\nexport const Transaction = objectType({\n  name: 'Transaction',\n  definition(t) {\n    t.model.id()\n    t.model.account()\n  },\n})\n```\n\n```text\nschema.prisma\n```\n\n```text\nNexus\n```\n\n========================================\n\nComments:\n- Did you fix that? How?","metadata":{"transformedAt":"2026-08-18T18:33:14.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":249,"estimatedTokens":1738}}159{"id":"stack-73175942","source":"stackoverflow","questionId":73175942,"title":"NPM Workspaces with two or more @prisma/client dependencies","tags":["npm","prisma","npm-workspaces"],"text":"Title: NPM Workspaces with two or more @prisma/client dependencies\nTags: npm, prisma, npm-workspaces\nSource: Stack Overflow\n\nQuestion:\nI have a monorepo setup. It looks something like this:\n\nproject\n\n- node_modules\npackages\n\nmy-first-project\n\nprisma\n\n- schema.prisma\n\nmy-second-project\n\nprisma\n\n- schema.prisma\n\nSo both projects (my-first-project and my-second-project) have @prisma/client installed and get there dependencies from the upper node_modules folder.\n\nThe thing is that whenever i change something in my schema.prisma file (e.g. in my-first-project) and run `npx prisma migrate dev --name whatever` it generates all the types and stuff and puts it in the upper node_modules folder. this leads to \"type not found\" errors on the other project (e.g. my-second-project).\n\nIs there a way to tell npm to keep some dependencies in a separate node_modules folder inside each project?\n\n========================================\n\nCode:\n```text\nnpx prisma migrate dev --name whatever\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"../src/generated/client\"\n}\n```\n\n```js\nimport { PrismaClient } from './generated/client'\n```\n\n```text\nPrismaClient\n```\n\n```text\nPrismaClient\n```\n\n```text\nnode_modules\n```\n\n========================================\n\nComments:\n- It is not clear to me from your example where I tell Prisma to build to an alternative location.\n- @ThaJay if you mean the `generator client ...` block, that is from the `schema.prisma` file.","metadata":{"transformedAt":"2026-08-18T18:33:14.832Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":65,"estimatedTokens":370}}160{"id":"stack-70806367","source":"stackoverflow","questionId":70806367,"title":"Prisma How to automatically update \"updatedAt\" field of parent element when a child element is created or updated?","tags":["node.js","server","backend","prisma"],"text":"Title: Prisma How to automatically update \"updatedAt\" field of parent element when a child element is created or updated?\nTags: node.js, server, backend, prisma\nSource: Stack Overflow\n\nQuestion:\nLet's say I have this schema:\n\n```\nmodel User {\n id String @id @default(cuid())\n name String\n email String\n profile Profile?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Profile {\n id Int @id @default(autoicrement())\n bio String?\n avatar String?\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n userId String @unique\n}\n```\n\nNow what I want to archive is, if a user's profile is updated, for example, a `bio` field is updated, I want the `updatedAt` field on `User` model to automatically reflect that and get updated too to the current timestamp.\n\nAny guide, hint or suggestion will be much appreciated!!\n\n========================================\n\nCode:\n```text\nmodel User {\n   id String @id @default(cuid())\n   name String\n   email String\n   profile Profile?\n   createdAt DateTime @default(now())\n   updatedAt DateTime @updatedAt\n}\n\nmodel Profile {\n   id Int @id @default(autoicrement())\n   bio String?\n   avatar String?\n   user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n   userId String @unique\n}\n```\n\n```text\nbio\n```\n\n```text\nupdatedAt\n```\n\n```text\nUser\n```\n\n```text\nconst updateUserProfile = (id, data) => {\n  return prisma.profile.update({\n    where: {\n      id\n    },\n    data: {\n      ...data,\n      user: {\n        update: {\n          updatedAt: new Date()\n        }\n      }\n    }\n  })\n}\n```\n\n========================================\n\nComments:\n- updatedAt is metadata for the User model. If you need to keep track of when the Profile is updated, you should put updatedAt DateTime @updatedAt on the profile itself. Updating the timestamp on parent model will just confuse developer debugging it in the future.\n- Hi hi, thanks for this. it looks to me like this will use the timestamp based on whatever is executing the prisma client, not on the server time, and is prone to causing bugs.\n- @fotoflo it will be executed on the server and it will use your server time of course, what bugs it can cause?\n- Sorry, to clarify, @Danila, it will be executed on the NodeJS (application) server, aka the Prisma client, not the MySQL or Postgres (database) server. Database servers have a now() function. You may run multiple application servers around the globe with different server times, but the database server's time should be the source of truth in the database. If it's not and you query based on time stamp -- you can see where this is going - you'll be returning times from different clocks - some of which may be set to the future or distant past.\n- thanks @Danila, sorry to say you are totally incorrect. Also rude, but hey it's the internet. Again, new Date() executes in the javascript runtime environment, while select now(); executes in the mysql runtime environment. I'll write the answer when i get.\n- @fotoflo It literally does not matter because date will be store in UTC anyway, so if you have 1 server in USA and 1 in Japan you can still do that, *unless* you server time is incorrect for some reason. If you have correct local server time set then it's all good.\n- The solution above is probably fine for a hobby project/small scale. But to illustrate the issue @fotoflo was saying: imagine you have 3 servers running the same application (e.g. NodeJS) behind a load balancer. All 3 servers will have slightly different time. Let's say: Now let's say Server 3 saves a record. `updatedAt` is +1. Now Server 1 reads `where updatedAt < ..` but the record was saved in the DB according to Server 3's time. There are other examples where this is problematic.\n- @EamonnGahan please don't try to make a completely different argument now and turn discussion upside down, @fotoflo was saying `servers around the globe with different server times`, not +-1 second issue. If you server time is incorrect then you are up for other issues as well, you can't use any date related business logic at all. Also this discussion is 100% unrelated to prisma and original question, if you have different/better answer to the question - just post it.\n- no i was talking generally we want to use the database server's now() function instead of the javascript runtime's time. @EamonnGahan has it right.\n- Why are you making the assumption that a server's region effects the timezone? Why would you ever have a server be anything but UTC? The whole premise of this argument makes no sense.","metadata":{"transformedAt":"2026-08-18T18:33:14.832Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":95,"estimatedTokens":1142}}161{"id":"stack-55824050","source":"stackoverflow","questionId":55824050,"title":"How to do a nested mutation resolver with nexus-prisma","tags":["graphql","prisma","prisma-graphql","nexus-prisma"],"text":"Title: How to do a nested mutation resolver with nexus-prisma\nTags: graphql, prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nI have the following datamodel:\n\n```\ntype Job { \n // ...\n example: String\n selections: [Selection!]\n // ...\n}\n\ntype Selection { \n ...\n question: String\n ...\n}\n```\n\nI define my object type so:\n\n```\nexport const Job = prismaObjectType({\n name: 'Job',\n definition(t) {\n t.prismaFields([\n // ...\n 'example',\n {\n name: 'selections',\n },\n // ...\n ])\n },\n})\n```\n\nI do my resolver this way:\n\n```\nt.field('createJob', {\n type: 'Job',\n args: {\n // ...\n example: stringArg(),\n selections: stringArg(),\n // ...\n },\n resolve: (parent, {\n example,\n selections\n }, ctx) => {\n // The resolver where I do a ctx.prisma.createJob and connect/create with example\n },\n})\n```\n\nSo now in the resolver I can receive the selections as json string and then parse it and connect/create with the job.\n\nThe mutation would look like this:\n\n```\nmutation {\n createJob(\n example: \"bla\"\n selections: \"ESCAPED JSON HERE\"\n ){\n id\n }\n}\n```\n\nI was wondering if there's anything more elegant where I could do something like:\n\n```\nmutation {\n createJob(\n example: \"bla\"\n selections: {\n question: \"bla\"\n }\n ){\n id\n }\n}\n```\n\nor \n\n```\nmutation {\n createJob(\n example: \"bla\"\n selections(data: {\n // ...\n })\n ){\n id\n }\n}\n```\n\nI've noticed that with nexus-prisma you can do `stringArg({list: true})` but you can't really do objects. \n\nMy main question is what is the most elegant way to do either nested mutation or connect all in one.\n\n========================================\n\nCode:\n```text\ntype Job { \n    // ...\n    example: String\n    selections: [Selection!]\n    // ...\n}\n\ntype Selection { \n    ...\n    question: String\n    ...\n}\n```\n\n```text\nexport const Job = prismaObjectType({\n  name: 'Job',\n  definition(t) {\n    t.prismaFields([\n      // ...\n      'example',\n      {\n        name: 'selections',\n      },\n      // ...\n    ])\n  },\n})\n```\n\n```text\nt.field('createJob', {\n  type: 'Job',\n  args: {\n    // ...\n    example: stringArg(),\n    selections: stringArg(),\n    // ...\n  },\n  resolve: (parent, {\n    example,\n    selections\n  }, ctx) => {\n    // The resolver where I do a ctx.prisma.createJob and connect/create with example\n  },\n})\n```\n\n```text\nmutation {\n  createJob(\n    example: \"bla\"\n    selections: \"ESCAPED JSON HERE\"\n  ){\n    id\n  }\n}\n```\n\n```text\nmutation {\n  createJob(\n    example: \"bla\"\n    selections: {\n       question: \"bla\"\n    }\n  ){\n    id\n  }\n}\n```\n\n```text\nmutation {\n  createJob(\n    example: \"bla\"\n    selections(data: {\n      // ...\n    })\n  ){\n    id\n  }\n}\n```\n\n```text\nstringArg({list: true})\n```\n\n```text\nexport const SomeFieldInput = inputObjectType({\n  name: \"SomeFieldInput\",\n  definition(t) {\n    t.string(\"name\", { required: true });\n    t.int(\"priority\");\n  },\n});\n```\n\n```text\nargs: {\n  input: arg({\n    type: \"SomeFieldInput\", // name should match the name you provided\n  }),\n}\n```\n\n```text\nconst Query = queryType({\n  definition(t) {\n    t.field('someField', {\n      type: 'String',\n      nullable: true,\n      args: {\n        input: arg({\n          type: \"SomeFieldInput\", // name should match the name you provided\n        }),\n      },\n      resolve: (parent, { input }) => {\n        return `You entered: ${input && input.name}`\n      },\n    })\n  },\n})\n\nconst SomeFieldInput = inputObjectType({\n  name: \"SomeFieldInput\",\n  definition(t) {\n    t.string(\"name\", { required: true });\n  },\n});\n\nconst schema = makeSchema({\n  types: {Query, SomeFieldInput},\n  outputs: {\n    ...\n  },\n});\n```\n\n```text\nquery {\n  someField(\n    input: {\n       name: \"Foo\"\n    }\n  )\n}\n```\n\n```text\nquery($input: SomeFieldInput) {\n  someField(input: $input)\n}\n```\n\n```text\ntypes\n```\n\n```text\nmakeSchema\n```\n\n```text\nlist\n```\n\n```text\nnullable\n```\n\n```text\ndescription\n```\n\n========================================\n\nComments:\n- This seems exactly what I need will review and probably assign bounty thanks a bunch! Is the documentation not very clear or is it me?? Thanks you!!\n- Yeah, `nexus` is pretty new and the docs are pretty sparse. They're accepting PRs for any corrections or additions to the docs though :)\n- FWIW I updated the answer with a more complete example schema\n- Hey! I never really checked since I had already implemented it the other way, I'm getting: `Error: Expected SomeFieldInput to be a valid output type, saw GraphQLInputObjectType` any ideas? Thanks! Sorry for the late reply!","metadata":{"transformedAt":"2026-08-18T18:33:14.832Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":296,"estimatedTokens":1108}}162{"id":"stack-67546789","source":"stackoverflow","questionId":67546789,"title":"Handle Prisma errors with Express","tags":["node.js","typescript","express","backend","prisma"],"text":"Title: Handle Prisma errors with Express\nTags: node.js, typescript, express, backend, prisma\nSource: Stack Overflow\n\nQuestion:\nI am having some issues with error handling using ExpressJS and Prisma. Whenever a Prisma Exception occurs, my entire Node application crashes, and I have to restart it. I have done some googling and have looked at the Prisma Docs for error handling, but I can't find any answers.\n\nI know I could possibly use `try` and `catch`, but this feels unnecessary, as I could handle this much better with an error handler, especially when a lot of information on errors is passed through Prisma.\n\nI have tried to implement the Express error handler like this:\n\n```\n// index.ts\n\nimport errorHandler from \"./middleware/errorHandler\";\n...\nserver.use(errorHandler);\n\n// errorHandler.ts\n\nimport { NextFunction, Response } from \"express\";\n\n// ts-ignore because next function is required for some weird reason\n// @ts-ignore\nconst errorHandler = (err: any, _: any, res: Response, next: NextFunction) => {\n console.error(err.stack);\n res.status(500).send(\"Internal Server Error\");\n};\n\nexport default errorHandler;\n```\n\nThis works fine for normal errors, but doesn't execute for Prisma errors, but instead just crashes the Node application.\n\nHow can I implement an error handler so I can manage Prisma Expections?\n\n========================================\n\nTop Answer:\nAs of now (Express As noted in the Express error handling docs:\n\nErrors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.\n\nFor errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them.\n\nYou absolutely can use your Express error handler with `try` and `catch` like so.\n\n```\ntry {\n await prismaOperation();\n} catch (e: unknown) {\n next(e);\n}\n```\n\nIf you pass anything to the next() function (except the string 'route'), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions.\n\nIf `prismaOperation` throws an error, the catch block will execute where you will have to manually pass the error to `next()`. Express will then skip all remaining middlewares and execute the error handler.\n\nStarting with Express 5, this behaviour will be automated, as noted in the docs:\n\nStarting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error.\n\n========================================\n\nCode:\n```text\n// index.ts\n\nimport errorHandler from \"./middleware/errorHandler\";\n...\nserver.use(errorHandler);\n\n// errorHandler.ts\n\nimport { NextFunction, Response } from \"express\";\n\n// ts-ignore because next function is required for some weird reason\n// @ts-ignore\nconst errorHandler = (err: any, _: any, res: Response, next: NextFunction) => {\n    console.error(err.stack);\n    res.status(500).send(\"Internal Server Error\");\n};\n\nexport default errorHandler;\n```\n\n```text\ntry\n```\n\n```text\ncatch\n```\n\n```text\ntry {\n  await prismaOperation();\n} catch(e) {\n  throw e; // avoid this which will crash our app\n  /* Process Prisma error with error codes\n     and prepare an appropriate error message\n  */\n  const error = prismaCustomErrorHandler(e);\n  res.send(error); // Sending response instead of passing it to our default handler\n}\n```\n\n```text\n...\nconst error = prismaCustomErrorHandler(e);\n  res.send(error); // Sending response instead of passing it to our default handler\n...\n\n// Edit: Or you could process and pass the error using `next(error)` to default error handler.\n```\n\n```text\n(err, req, res, next)\n```\n\n```text\n(req, res, next)\n```\n\n```text\n(err, _, res)\n```\n\n```text\nerr\n```\n\n```text\nreq\n```\n\n```text\n_\n```\n\n```text\nres\n```\n\n```text\nres\n```\n\n```text\nnext\n```\n\n```text\nnext\n```\n\n```text\nres.send\n```\n\n```text\ntry {\n  await prismaOperation();\n} catch (e: unknown) {\n  next(e);\n}\n```\n\n```text\nnext()\n```\n\n```text\ntry\n```\n\n```text\ncatch\n```\n\n```text\nprismaOperation\n```\n\n```text\nnext()\n```\n\n```text\n@Module({\n  imports: [UsersModule, AuthModule, DealershipModule],\n  controllers: [],\n  providers: [\n    PrismaService,\n    {\n      provide: APP_FILTER,\n      useClass: HttpExceptionFilter,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n```text\napp.useGlobalFilters(new HttpExceptionFilter());\n```\n\n========================================\n\nComments:\n- @SamTheFam Take a look at this npmjs.com/package/express-async-errors","metadata":{"transformedAt":"2026-08-18T18:33:14.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":212,"estimatedTokens":1144}}163{"id":"stack-72287783","source":"stackoverflow","questionId":72287783,"title":"Can i create multiple schema in prisma for each model?","tags":["schema","prisma"],"text":"Title: Can i create multiple schema in prisma for each model?\nTags: schema, prisma\nSource: Stack Overflow\n\nQuestion:\nThis is a default structure of prisma schema...\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n username String @unique @db.VarChar(255)\n role UserRole @default(admin)\n posts Post[]\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String \n post String @db.VarChar(500)\n created_at DateTime @default(now())\n updated_at DateTime @updatedAt\n user_id Int\n user User @relation(fields: [user_id], references: [id])\n}\n\n//custom enums\nenum UserRole {\n client\n admin\n}\n```\n\nI want to create multiple schema for each models. User schema for user model, Post schema for post model. Like we use models in mongoose. Is it possible in Prisma ORM?\n\n========================================\n\nTop Answer:\nPrisma `multiSchema` is now supported as a preview feature.\n\nSee here https://www.prisma.io/docs/guides/database/multi-schema\n\nIt was introduced in version `4.3.0` https://github.com/prisma/prisma/issues/1122#issuecomment-1231773471\n\nAs the docs say you would add the preview feature...\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"multiSchema\"]\n}\n```\n\nThen in your `datasource` you note the schemas...\n\n```\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n schemas = [\"User\", \"Post\"]\n}\n```\n\nAnd finally in each model you add the `@@schema` attribute...\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n username String @unique @db.VarChar(255)\n role UserRole @default(admin)\n posts Post[]\n\n @@schema(\"User\")\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String \n post String @db.VarChar(500)\n created_at DateTime @default(now())\n updated_at DateTime @updatedAt\n user_id Int\n user User @relation(fields: [user_id], references: [id])\n\n @@schema(\"Post\")\n}\n```\n\nNote:\n\nIt might not be possible to do cross schema foreign keys. I saw it mentioned somewhere, but I can't find it now.\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel User {\n  id Int  @id @default(autoincrement())\n  username String @unique @db.VarChar(255)\n  role UserRole @default(admin)\n  posts Post[]\n}\n\nmodel Post {\n  id Int @id @default(autoincrement())\n  title String \n  post String @db.VarChar(500)\n  created_at DateTime @default(now())\n  updated_at DateTime @updatedAt\n  user_id Int\n  user User @relation(fields: [user_id], references: [id])\n}\n\n//custom enums\nenum UserRole {\n  client\n  admin\n}\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  previewFeatures = [\"multiSchema\"]\n}\n```\n\n```text\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n  schemas  = [\"User\", \"Post\"]\n}\n```\n\n```text\nmodel User {\n  id Int  @id @default(autoincrement())\n  username String @unique @db.VarChar(255)\n  role UserRole @default(admin)\n  posts Post[]\n\n  @@schema(\"User\")\n}\n\nmodel Post {\n  id Int @id @default(autoincrement())\n  title String \n  post String @db.VarChar(500)\n  created_at DateTime @default(now())\n  updated_at DateTime @updatedAt\n  user_id Int\n  user User @relation(fields: [user_id], references: [id])\n\n  @@schema(\"Post\")\n}\n```\n\n```text\nmultiSchema\n```\n\n```text\n4.3.0\n```\n\n```text\ndatasource\n```\n\n```text\n@@schema\n```\n\n========================================\n\nComments:\n- Related issue on prisma: github.com/prisma/prisma/issues/2377 , looks like it is not officially supported currently, but there are 3rd party workarounds like prisma-merge","metadata":{"transformedAt":"2026-08-18T18:33:14.832Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":195,"estimatedTokens":925}}164{"id":"stack-70474736","source":"stackoverflow","questionId":70474736,"title":"NextAuth Credential Provider with Prisma Adapter in Next12 does nothing","tags":["database","next.js","adapter","prisma","next-auth"],"text":"Title: NextAuth Credential Provider with Prisma Adapter in Next12 does nothing\nTags: database, next.js, adapter, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI've setup my **Nextjs (Next12)** with **NextAuth CredentialsProvider** and use **Prisma Adapter** to persist user's session in the database.\n\nI followed this documentation here from NextAuth team themselves. But **nothing happen** after I clicked on login button.\n\n### To Note\n\nBefore that:-\n\n- I've make sure to try get the data first from the database & it works just fine.\n\n- I did also did try to just use the normal `session: { jwt: true, maxAge: 30 * 24 * 60 * 60 }` instead of straight away use **Adapter**. Also works fine.\n\n### Question\n\nNow, I just want to know whether it's possible or not to use `CredentialsProvider` with `Adapter` at all?\n\n### NextAuth API\n\nBelow are 2 examples or working one and not working one: `/pages/api/auth/[...nextauth].js`\n\n- **working**: does not use `adapter`\n\n```\nimport NextAuth from 'next-auth';\nimport CredentialsProvider from 'next-auth/providers/credentials';\n\nexport default async function auth(req, res) {\n return await NextAuth(req, res, {\n secret: process.env.SECRET,\n adapter: PrismaAdapter(prisma),\n session: {\n jwt: true,\n maxAge: 30 * 24 * 60 * 60, // 30 days\n }\n providers: [\n CredentialsProvider({\n async authorize(credentials) {\n const user = await prisma.user.findFirst({\n where: {\n email: credentials.email,\n password: credentials.password\n }\n });\n\n if (user !== null)\n {\n return user;\n }\n else {\n throw new Error('User does not exists. Please make sure you insert the correct email & password.')\n }\n }\n })\n ],\n callbacks: {\n redirect: async ({ url, baseUrl }) => {\n return baseUrl\n },\n jwt: async ({ token, user, account, profile, isNewUser }) => {\n if (typeof user !== typeof undefined) token.user = user;\n \n return token\n },\n session: async ({ session, user, token }) => {\n token?.user && (session.user = token.user)\n \n return session\n }\n }\n })\n}\n```\n\n- **not working**: using `prisma adapter`\n\n```\nimport { PrismaAdapter } from \"@next-auth/prisma-adapter\";\nimport { PrismaClient } from '@prisma/client';\nimport NextAuth from 'next-auth';\nimport CredentialsProvider from 'next-auth/providers/credentials';\nconst prisma = new PrismaClient()\n\nexport default async function auth(req, res) {\n return await NextAuth(req, res, {\n secret: process.env.SECRET,\n adapter: PrismaAdapter(prisma),\n providers: [\n CredentialsProvider({\n async authorize(credentials) {\n const user = await prisma.user.findFirst({\n where: {\n email: credentials.email,\n password: credentials.password\n }\n });\n\n if (user !== null)\n {\n return user;\n }\n else {\n throw new Error('User does not exists. Please make sure you insert the correct email & password.')\n }\n }\n })\n ],\n callbacks: {\n redirect: async ({ url, baseUrl }) => {\n return baseUrl\n },\n jwt: async ({ token, user, account, profile, isNewUser }) => {\n if (typeof user !== typeof undefined) token.user = user;\n \n return token\n },\n session: async ({ session, user, token }) => {\n token?.user && (session.user = token.user)\n \n return session\n }\n }\n })\n}\n```\n\n### Prisma Schema\n\nThis is the current `schema.prisma` (this comes from the NextAuth doc itself):-\n\n- I already did the `npx prisma migrate dev` & `npx prisma generate`\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"referentialIntegrity\"]\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n // shadowDatabaseUrl = env(\"SHADOW_URL\")\n referentialIntegrity = \"prisma\"\n}\n\nmodel Account {\n id String @id @default(cuid())\n userId String\n type String\n provider String\n providerAccountId String\n refresh_token String?\n access_token String?\n expires_at Int?\n token_type String?\n scope String?\n id_token String?\n session_state String?\n oauth_token_secret String?\n oauth_token String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@unique([provider, providerAccountId])\n}\n\nmodel Session {\n id String @id @default(cuid())\n sessionToken String @unique\n userId String\n expires DateTime\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n\nmodel User {\n id String @id @default(cuid())\n name String?\n email String? @unique\n password String?\n emailVerified DateTime?\n image String?\n accounts Account[]\n sessions Session[]\n}\n\nmodel VerificationToken {\n identifier String\n token String @unique\n expires DateTime\n\n @@unique([identifier, token])\n}\n```\n\n========================================\n\nCode:\n```js\nimport NextAuth from 'next-auth';\nimport CredentialsProvider from 'next-auth/providers/credentials';\n\nexport default async function auth(req, res) {\n  return await NextAuth(req, res, {\n    secret: process.env.SECRET,\n    adapter: PrismaAdapter(prisma),\n    session: {\n      jwt: true,\n      maxAge: 30 * 24 * 60 * 60, // 30 days\n    }\n    providers: [\n      CredentialsProvider({\n        async authorize(credentials) {\n          const user = await prisma.user.findFirst({\n            where: {\n                email: credentials.email,\n                password: credentials.password\n            }\n          });\n\n          if (user !== null)\n          {\n              return user;\n          }\n          else {\n            throw new Error('User does not exists. Please make sure you insert the correct email & password.')\n          }\n        }\n      })\n    ],\n    callbacks: {\n      redirect: async ({ url, baseUrl }) => {\n        return baseUrl\n      },\n      jwt: async ({ token, user, account, profile, isNewUser }) => {\n        if (typeof user !== typeof undefined) token.user = user;\n  \n        return token\n      },\n      session: async ({ session, user, token }) => {\n        token?.user && (session.user = token.user)\n  \n        return session\n      }\n    }\n  })\n}\n```\n\n```js\nimport { PrismaAdapter } from \"@next-auth/prisma-adapter\";\nimport { PrismaClient } from '@prisma/client';\nimport NextAuth from 'next-auth';\nimport CredentialsProvider from 'next-auth/providers/credentials';\nconst prisma = new PrismaClient()\n\nexport default async function auth(req, res) {\n  return await NextAuth(req, res, {\n    secret: process.env.SECRET,\n    adapter: PrismaAdapter(prisma),\n    providers: [\n      CredentialsProvider({\n        async authorize(credentials) {\n          const user = await prisma.user.findFirst({\n            where: {\n                email: credentials.email,\n                password: credentials.password\n            }\n          });\n\n          if (user !== null)\n          {\n              return user;\n          }\n          else {\n            throw new Error('User does not exists. Please make sure you insert the correct email & password.')\n          }\n        }\n      })\n    ],\n    callbacks: {\n      redirect: async ({ url, baseUrl }) => {\n        return baseUrl\n      },\n      jwt: async ({ token, user, account, profile, isNewUser }) => {\n        if (typeof user !== typeof undefined) token.user = user;\n  \n        return token\n      },\n      session: async ({ session, user, token }) => {\n        token?.user && (session.user = token.user)\n  \n        return session\n      }\n    }\n  })\n}\n```\n\n```js\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"referentialIntegrity\"]\n}\n\ndatasource db {\n  provider             = \"mysql\"\n  url                  = env(\"DATABASE_URL\")\n  // shadowDatabaseUrl    = env(\"SHADOW_URL\")\n  referentialIntegrity = \"prisma\"\n}\n\nmodel Account {\n  id                 String  @id @default(cuid())\n  userId             String\n  type               String\n  provider           String\n  providerAccountId  String\n  refresh_token      String?\n  access_token       String?\n  expires_at         Int?\n  token_type         String?\n  scope              String?\n  id_token           String?\n  session_state      String?\n  oauth_token_secret String?\n  oauth_token        String?\n\n  user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n  @@unique([provider, providerAccountId])\n}\n\nmodel Session {\n  id           String   @id @default(cuid())\n  sessionToken String   @unique\n  userId       String\n  expires      DateTime\n  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n\nmodel User {\n  id            String    @id @default(cuid())\n  name          String?\n  email         String?   @unique\n  password      String?\n  emailVerified DateTime?\n  image         String?\n  accounts      Account[]\n  sessions      Session[]\n}\n\nmodel VerificationToken {\n  identifier String\n  token      String   @unique\n  expires    DateTime\n\n  @@unique([identifier, token])\n}\n```\n\n```text\nsession: { jwt: true, maxAge: 30 * 24 * 60 * 60 }\n```\n\n```text\nCredentialsProvider\n```\n\n```text\nAdapter\n```\n\n```text\n/pages/api/auth/[...nextauth].js\n```\n\n```text\nadapter\n```\n\n```text\nprisma adapter\n```\n\n```text\nschema.prisma\n```\n\n```text\nnpx prisma migrate dev\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nCredentialsProvider\n```\n\n```text\nnext-auth\n```\n\n```text\nadapter\n```\n\n```text\nCredentialsProvider\n```\n\n========================================\n\nComments:\n- So, how to persist session in db, using prisma let's say?\n- @killjoy Based on the docs. Only when using `CredentialsProvider` you can't persist session in db. Basically you can use any adapter. Doesn't have to be prisma.\n- this design is correct and makes total sense because if you are using Credentials, you can just save directly to DB, why use an adapter? The reason for adapters is that they allow you to get access to the user data not coming from your web app.","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":428,"estimatedTokens":2433}}165{"id":"stack-72613866","source":"stackoverflow","questionId":72613866,"title":"Prisma Multiple 1-n relations on same model","tags":["prisma"],"text":"Title: Prisma Multiple 1-n relations on same model\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a model so that a user can own multiple Titles and equip one of them.\n\nThe problem is that it does register on the title side, but it does not on the individual user side when I try to query its current title.\n\nThe following is how I've built it :\n\n```\nmodel User {\n id String @id @default(cuid())\n titles Title[] @relation(\"titles\")\n currentTitle Title? @relation(\"currentTitle\", fields: [currentTitleId], references: [id])\n currentTitleId String?\n}\n\nmodel Title {\n id String @id @default(cuid())\n name String?\n users User[] @relation(\"titles\")\n currentUsers User[] @relation(\"currentTitle\")\n}\n```\n\nIs my schema right or did I miss something ?\nThanks for your help !\n\n========================================\n\nCode:\n```text\nmodel User {\n  id          String   @id @default(cuid())\n  titles            Title[]    @relation(\"titles\")\n  currentTitle      Title?     @relation(\"currentTitle\", fields: [currentTitleId], references: [id])\n  currentTitleId    String?\n}\n\nmodel Title {\n  id           String  @id @default(cuid())\n  name         String?\n  users        User[]  @relation(\"titles\")\n  currentUsers User[]  @relation(\"currentTitle\")\n}\n```\n\n```js\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n  const user = await prisma.user.create({\n    data: {},\n  });\n\n  console.log(user);\n\n  const title = await prisma.title.create({\n    data: {\n      name: 'Prisma',\n    },\n  });\n\n  console.log(title);\n\n  const assignTitle = await prisma.user.update({\n    where: {\n      id: 'cl4e0gqai0000op78b2apaere',\n    },\n    data: {\n      currentTitleId: 'cl4e0gqbm0007op78xusxlkf7',\n    },\n  });\n\n  console.log(assignTitle);\n\n  const getCurrentTitle = await prisma.user.findFirst({\n    where: {\n      id: 'cl4e0gqai0000op78b2apaere',\n    },\n    select: {\n      currentTitle: true,\n    },\n  });\n\n  console.log(getCurrentTitle);\n}\n\nmain()\n  .catch((e) => {\n    throw e;\n  })\n  .finally(async () => {\n    await prisma.$disconnect();\n  });\n```\n\n```json\n{ currentTitle: { id: 'cl4e0gqbm0007op78xusxlkf7', name: 'Prisma' } }\n```\n\n========================================\n\nComments:\n- yep indeed it's working, it was a mistake in an other part of the code, thanks !","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":109,"estimatedTokens":581}}166{"id":"stack-71445312","source":"stackoverflow","questionId":71445312,"title":"For Prisma Client join queries is it possible to move deeply nested fields to top level of result?","tags":["javascript","json","prisma"],"text":"Title: For Prisma Client join queries is it possible to move deeply nested fields to top level of result?\nTags: javascript, json, prisma\nSource: Stack Overflow\n\nQuestion:\nDoes Prisma have the ability to move nested fields from another table join to the top level of the result, like a flattened view? I want to put the result JSON into a frontend table without digging through nested objects and building another object.\n\nFor example I want to replicate this behavior where I can pick and choose the columns from different tables (columns from User, and School). Currently I use a raw query with a similar SQL, however I wonder if it's possible with using only the Prisma API:\n\n```\nSELECT \nu.id\n, u.email\n, s.school_name\nFROM \"User\" AS u\nJOIN \"UserSchool\" AS us ON us.user_id = u.id\nJOIN \"School\" AS s ON s.id = us.school_id\n```\n\n```\nid | email | school_name\n123| student1@email.com | mount high\n\nI want JSON that looks like this:\n{\n \"id\": \"1\",\n \"email\": \"student1@email.com\",\n \"school_name\": \"mount high\",\n}\n```\n\nIf I did this in Prisma, I would need to go into several levels of nested objects to get the same column name on another table for e.g. `user[user_school][schoo][school_name]`. This requires extra work to loop through all my results, extract from the nested object, and build another object. This example isn't too bad, but I have more joins and deeply nested objects for my actual problem (lots of association/lookup tables). I've experimented with the `select` and `include` for my joins, but they are structured with the nested JSON.\n\n```\nusers = await prisma.user.findMany({\n include: {\n user_school: {\n include: {\n school: true,\n },\n },\n },\n```\n\n```\n{\n \"id\": \"1\",\n \"email\": \"student1@email.com\",\n \"user_school\": [\n {\n \"id\": 1,\n \"user_id\": \"1\",\n \"school_id\": \"1\",\n \"school\": {\n \"id\": 1,\n \"school_name\": \"mountain high\",\n }\n }\n ],\n}\n```\n\n========================================\n\nCode:\n```text\nSELECT \nu.id\n, u.email\n, s.school_name\nFROM \"User\" AS u\nJOIN \"UserSchool\" AS us ON us.user_id = u.id\nJOIN \"School\" AS s ON s.id = us.school_id\n```\n\n```text\nid | email              | school_name\n123| student1@email.com | mount high\n\nI want JSON that looks like this:\n{\n        \"id\": \"1\",\n        \"email\": \"student1@email.com\",\n        \"school_name\": \"mount high\",\n}\n```\n\n```text\nusers = await prisma.user.findMany({\n        include: {\n          user_school: {\n            include: {\n              school: true,\n            },\n          },\n        },\n```\n\n```text\n{\n        \"id\": \"1\",\n        \"email\": \"student1@email.com\",\n        \"user_school\": [\n            {\n                \"id\": 1,\n                \"user_id\": \"1\",\n                \"school_id\": \"1\",\n                \"school\": {\n                    \"id\": 1,\n                    \"school_name\": \"mountain high\",\n                }\n            }\n        ],\n}\n```\n\n```text\nuser[user_school][schoo][school_name]\n```\n\n```text\nselect\n```\n\n```text\ninclude\n```\n\n```text\nflatten:true\n```\n\n========================================\n\nComments:\n- Thanks. Good to know! I'll go ahead and do that.","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":136,"estimatedTokens":761}}167{"id":"stack-74875231","source":"stackoverflow","questionId":74875231,"title":"node.js | Replacing DB client with Prisma keeping preserving DB structure - issue with uuid_generate_v4()","tags":["node.js","postgresql","uuid","prisma","postgresql-10"],"text":"Title: node.js | Replacing DB client with Prisma keeping preserving DB structure - issue with uuid_generate_v4()\nTags: node.js, postgresql, uuid, prisma, postgresql-10\nSource: Stack Overflow\n\nQuestion:\nI am trying to add the Prisma DB client to the existing node.js project while preserving the DB structure.\n\nPostgresql\nPrisma 4.7.1\n\n- I've set up the initial Prisma configuration (env vars, etc.).\n\n- I've used the command `npx prisma db pull` to generate `prisma.schema` file according to the existing DB structure\n\n- I create the initial migration by using some empty DB `npx prisma migrate dev`\n\nAt this point it is expected that migration would create DB structure, but the command fails with the following error\n\n```\n✗ npx prisma migrate dev \nEnvironment variables loaded from .env\nPrisma schema loaded from prisma/schema.prisma\nDatasource \"db\": PostgreSQL database \"service_prisma\", schema \"public\" at \"127.0.0.1:5432\"\n\nPostgreSQL database service_prisma created at 127.0.0.1:5432\n\n✔ Enter a name for the new migration: … init\nApplying migration `20221221095823_init`\nError: P3018\n\nA migration failed to apply. New migrations cannot be applied before the error is recovered from. Read more about how to resolve migration issues in a production database: https://pris.ly/d/migrate-resolve\n\nMigration name: 20221221095823_init\n\nDatabase error code: 42883\n\nDatabase error:\nERROR: function uuid_generate_v4() does not exist\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.\n\nDbError { severity: \"ERROR\", parsed_severity: Some(Error), code: SqlState(E42883), message: \"function uuid_generate_v4() does not exist\", detail: None, hint: Some(\"No function matches the given name and argument types. You might need to add explicit type casts.\"), position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some(\"parse_func.c\"), line: Some(521), routine: Some(\"ParseFuncOrColumn\") }\n```\n\n up plan would be to:\n\n- Set DB back to the original one containing tables and data\n\n- Then mark initial migration as applied with the following command `npx prisma migrate resolve --applied 20221221095823_init`\n\nSo, main problem is that IDs in existing tables use uuid_generate_v4() to generate random UUID for new entries. The support on DB level is definitly there, because it simple works normally with slonik DB client.\n\n```\nmodel SomeTable {\n id String @id @default(dbgenerated(\"uuid_generate_v4()\")) @db.Uuid\n}\n```\n\nAny idea how to solve this? Thanks in advance!\n\n========================================\n\nCode:\n```text\n✗ npx prisma migrate dev              \nEnvironment variables loaded from .env\nPrisma schema loaded from prisma/schema.prisma\nDatasource \"db\": PostgreSQL database \"service_prisma\", schema \"public\" at \"127.0.0.1:5432\"\n\nPostgreSQL database service_prisma created at 127.0.0.1:5432\n\n✔ Enter a name for the new migration: … init\nApplying migration `20221221095823_init`\nError: P3018\n\nA migration failed to apply. New migrations cannot be applied before the error is recovered from. Read more about how to resolve migration issues in a production database: https://pris.ly/d/migrate-resolve\n\nMigration name: 20221221095823_init\n\nDatabase error code: 42883\n\nDatabase error:\nERROR: function uuid_generate_v4() does not exist\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.\n\nDbError { severity: \"ERROR\", parsed_severity: Some(Error), code: SqlState(E42883), message: \"function uuid_generate_v4() does not exist\", detail: None, hint: Some(\"No function matches the given name and argument types. You might need to add explicit type casts.\"), position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some(\"parse_func.c\"), line: Some(521), routine: Some(\"ParseFuncOrColumn\") }\n```\n\n```text\nmodel SomeTable {\n  id    String   @id @default(dbgenerated(\"uuid_generate_v4()\")) @db.Uuid\n}\n```\n\n```text\nnpx prisma db pull\n```\n\n```text\nprisma.schema\n```\n\n```text\nnpx prisma migrate dev\n```\n\n```text\nnpx prisma migrate resolve --applied 20221221095823_init\n```\n\n```text\nCREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\n```\n\n```text\nnpx prisma migrate dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":116,"estimatedTokens":1065}}168{"id":"stack-74520523","source":"stackoverflow","questionId":74520523,"title":"How to run migrations on a remote/cloud managed DB? (through CI/CD)","tags":["database","amazon-web-services","migration","continuous-deployment","prisma"],"text":"Title: How to run migrations on a remote/cloud managed DB? (through CI/CD)\nTags: database, amazon-web-services, migration, continuous-deployment, prisma\nSource: Stack Overflow\n\nQuestion:\n**TL;DR**\n\nWhat is the optimal flow / best practice to run migrations in a CI/CD pipeline against a database without public endpoint?\n\n`GH actions -> connect to remote db (somehow) -> run migration on said db` and how to rollback when deployment failed.\n\n**Problem**\n\nI need to setup a flow to deploy an application and it's database migrations accordingly.\nThe main issue I come across is that it's best practice to set the database to run **without** having a public endpoint, in a private VPC that matches the application service.\nBut how does one run migrations from a CI/CD pipeline in this case?\n\n**Current scenario**\n\nThe stack here is `nodejs`, `typeorm`, Elastic Beanstalk (EBS) & AWS.\n\n- Build docker image application code & push to private ECR (`app/dev-api:latest`)\n\n- Build separate docker that packages the migrations and push it to a separate private ECR. `dbmigrations/dev:latest`\n\n- As soon as the migrations image is pushed to `dbmigrations/dev:latest`, a `fargate` service boots up that sits in the same VPC as the RDS and runs the migrations.\nIf that `fargate` task runned succesfully, deploy applicationcode to Elastic Beanstalk\n\na) If something goes wrong during deploy to EBS\n\n- build new docker image\n\n- push to another ECR that contains \"rollback\" migration\n\n- boot up another fargate service\n\n- b) Exit if all tasks ran succesfully -> Deploy Succesful.\n\n**Next scenario**\n\nNow I'm using following stack: `nodejs`, `prisma` and \"App Runner\", \"RDS\" on AWS.\n\nI would like to run the database in a private VPC still, but I'm not sure how I would run `prisma` migrations against a private database.\nAlso I would think there is a simpler solution than to run separate docker containers to run your database migrations, as this can cause a miss-sync between the deployed application and the database.\n\nI know there are tools like `liquibase` & `flyway` but both are paid (I think), and since `prisma` comes with a migration flow itself, I don't see why I would need *yet another* migration tool to do such task.\n\nThanks in advance!\n\nPS: I'm using Github Actions, but I'm more looking to a general flow. I'm not looking for a code example (as I'm sure this will apply to other pipeline services as well)\n\n========================================\n\nCode:\n```text\nGH actions -> connect to remote db (somehow) -> run migration on said db\n```\n\n```text\nnodejs\n```\n\n```text\ntypeorm\n```\n\n```text\napp/dev-api:latest\n```\n\n```text\ndbmigrations/dev:latest\n```\n\n```text\ndbmigrations/dev:latest\n```\n\n```text\nfargate\n```\n\n```text\nfargate\n```\n\n```text\nnodejs\n```\n\n```text\nprisma\n```\n\n```text\nprisma\n```\n\n```text\nliquibase\n```\n\n```text\nflyway\n```\n\n```text\nprisma\n```\n\n========================================\n\nComments:\n- Session Manager looks very promising. Although, I'm currently stuck here, and none of the solutions seem to be fixing the issue. Any experience with it yourself? I followed this guide front to back and back to front:aws.amazon.com/blogs/database/&hellip; same issue: stackoverflow.com/questions/64001338/&hellip;\n- Sorry, maybe I wasn't clear. You can't connect to RDS with session manager without bastion. That would be against networking good practices. Session manager just provides better solution over standard ssh connection to bastion.\n- I got that :) I setup a bastion with the guide (first link). However the connection still isn't working as the guide shows. Everything I tried, I get \"targetnotconnected\"\n- Some part of networking is probably still blocking. Try to connect just to bastion, than from bastion to rds. You can get more info from CloudTrail","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":117,"estimatedTokens":944}}169{"id":"stack-55446867","source":"stackoverflow","questionId":55446867,"title":"How to set Auth token cookie from GraphQL Mutation with Apollo","tags":["reactjs","cookies","graphql","apollo","prisma"],"text":"Title: How to set Auth token cookie from GraphQL Mutation with Apollo\nTags: reactjs, cookies, graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using GraphQLServer from graphql-yoga to handle requests. My back-end is able to communicate with my React front-end at this point and I can make graphql queries and get the response just fine.\n\nI was recently informed that I should be setting a cookie with the token, rather than returning it in the mutation response. So I'm trying to switch over but the cookie isn't being set by the mutation.\n\n***server.js*** (node)\n\n```\nimport { GraphQLServer, PubSub } from 'graphql-yoga';\nimport {resolvers, fragmentReplacements} from './resolvers/index'\nimport prisma from './prisma'\n\nconst pubsub = new PubSub()\n\nexport default new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context(request) {\n return {\n pubsub,\n prisma,\n request, //fragmentReplacements[], request, response\n }\n },\n fragmentReplacements\n});\n```\n\n***Mutation.js*** (node)\n\n```\nexport default {\n async createUser(parent, args, {prisma, request}, info) {\n const lastActive = new Date().toISOString()\n const user = await prisma.mutation.createUser({ data: {...args.data, lastActive }})\n const token = generateToken(user.id)\n const options = {\n maxAge: 1000 * 60 * 60 * 24, //expires in a day\n // httpOnly: true, // cookie is only accessible by the server\n // secure: process.env.NODE_ENV === 'prod', // only transferred over https\n // sameSite: true, // only sent for requests to the same FQDN as the domain in the cookie\n }\n const cookie = request.response.cookie('token', token, options)\n console.log(cookie)\n return {user}\n },\n // more mutations...\n```\n\nhttps://i.sstatic.net/USsiz.png\n\nconsole.log(cookie) outputs with the cookie attached\n\n***index.js*** (react)\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './components/App';\nimport ApolloClient, { InMemoryCache, create } from 'apollo-boost';\nimport {ApolloProvider} from 'react-apollo'\n\nconst client = new ApolloClient({\n uri: 'http://localhost:4000',\n cache: new InMemoryCache(),\n credentials: 'include',\n request: async operation => {\n operation.setContext({\n fetchOptions: {\n credentials: 'same-origin'\n }\n })\n },\n})\n\nReactDOM.render(\n \n \n , \n document.getElementById('root'));\n```\n\nSo my questions are:\n\n- **Is there a better way to do authentication with GraphQL**, or is setting the token with a cookie in the auth mutation suitable?\n\n- Assuming it's a decent approach, **how can I set the cookie from the mutation**?\n\nThanks for your time!\n\n========================================\n\nCode:\n```text\nimport { GraphQLServer, PubSub } from 'graphql-yoga';\nimport {resolvers, fragmentReplacements} from './resolvers/index'\nimport prisma from './prisma'\n\nconst pubsub = new PubSub()\n\nexport default new GraphQLServer({\n  typeDefs: './src/schema.graphql',\n  resolvers,\n  context(request) {\n    return {\n      pubsub,\n      prisma,\n      request, //fragmentReplacements[], request, response\n    }\n  },\n  fragmentReplacements\n});\n```\n\n```text\nexport default {\n  async createUser(parent, args, {prisma, request}, info) {\n    const lastActive = new Date().toISOString()\n    const user = await prisma.mutation.createUser({ data: {...args.data, lastActive }})\n    const token = generateToken(user.id)\n    const options = {\n      maxAge: 1000 * 60 * 60 * 24, //expires in a day\n      // httpOnly: true, // cookie is only accessible by the server\n      // secure: process.env.NODE_ENV === 'prod', // only transferred over https\n      // sameSite: true, // only sent for requests to the same FQDN as the domain in the cookie\n    }\n    const cookie = request.response.cookie('token', token, options)\n    console.log(cookie)\n    return {user}\n  },\n  // more mutations...\n```\n\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './components/App';\nimport ApolloClient, { InMemoryCache, create } from 'apollo-boost';\nimport {ApolloProvider} from 'react-apollo'\n\nconst client = new ApolloClient({\n  uri: 'http://localhost:4000',\n  cache: new InMemoryCache(),\n  credentials: 'include',\n  request: async operation => {\n    operation.setContext({\n      fetchOptions: {\n        credentials: 'same-origin'\n      }\n    })\n  },\n})\n\nReactDOM.render(\n  <ApolloProvider client={client}>\n    <App />\n  </ApolloProvider>, \n  document.getElementById('root'));\n```\n\n```text\nfetchOptions: {\n    credentials: 'include'\n }\n```\n\n========================================\n\nComments:\n- The way that you set the cookie is correct, I have successfully set cookies this way from an Express app. When you say that it is \"not set\", what do you mean exactly? Is it not visible in the developer console in the UI? Regarding the first question - you can use JWT and return the token as part of the response rather than a cookie. It appears to be the standard authentication/authorisation mechanism in GraphQL, I have managed to implement this successfully in the past.\n- Returning the token and using it directly in subsequent requests is not advisable in a browser-based client as it can be stolen by an attacker using JS, whereas cookies set with HTTPOnly and Secure flags cannot be accessed by JS.\n- @Jaryl Thanks, went with using the secure same-domain cookie.","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":178,"estimatedTokens":1332}}170{"id":"stack-64293094","source":"stackoverflow","questionId":64293094,"title":"Error Assertion `args[3]->IsInt32()' failed","tags":["node.js","typescript","graphql","prisma","prisma-graphql"],"text":"Title: Error Assertion `args[3]->IsInt32()' failed\nTags: node.js, typescript, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\n- **Version**: v12.19.0\n\n- **Platform**: Linux ayungavis 5.4.0-48-generic #52~18.04.1-Ubuntu SMP Thu Sep 10 12:50:22 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux\n\n- **Subsystem**:\n\n### What steps will reproduce the bug?\n\nI tried to the tutorial from Adding a Database to GraphQL, this is the code of my `script.ts`:\n\n```\nconst { PrismaClient } = require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function main() {\n const allLinks = await prisma.link.findMany()\n console.log(allLinks)\n}\n\nmain()\n .catch(e => {\n throw e\n })\n .finally(async () => {\n await prisma.disconnect()\n })\n```\n\n### How often does it reproduce? Is there a required condition?\n\nEverytime when I run it using `node src/script.ts` or `ts-node src/script.ts`.\n\nThe requirements:\n\n- @prisma/cli\n\n- @prisma/client\n\n### What is the expected behavior?\n\nShow all links from the database using prisma client.\n\n### What do you see instead?\n\nI tried to run the `script.ts` using `node src/script.ts` and `ts-node src/script.ts` but show the following error:\n\n```\n/usr/bin/node[20367]: ../src/node_http_parser_impl.h:529:static void node::{anonymous}::Parser::Initialize(const v8::FunctionCallbackInfo&): Assertion `args[3]->IsInt32()' failed.\n 1: 0xa17c40 node::Abort() [/usr/bin/node]\n 2: 0xa17cbe [/usr/bin/node]\n 3: 0xa3214a [/usr/bin/node]\n 4: 0xc019e9 [/usr/bin/node]\n 5: 0xc037d7 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [/usr/bin/node]\n 6: 0x1409319 [/usr/bin/node]\n```\n\n### Additional information\n\nThis is my `package.json` file:\n\n```\n{\n \"name\": \"learn\",\n \"version\": \"1.0.0\",\n \"description\": \"A GraphQL Server from scratch for learning purpose.\",\n \"main\": \"index.ts\",\n \"scripts\": {\n \"start\": \"dotenv -- nodemon -e ts,graphql -x ts-node src/index.ts\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"keywords\": [],\n \"dependencies\": {\n \"graphql-yoga\": \"^1.18.3\"\n },\n \"devDependencies\": {\n \"@prisma/cli\": \"^2.8.1\",\n \"@prisma/client\": \"^2.8.1\",\n \"@types/node\": \"^14.11.2\",\n \"dotenv-cli\": \"^4.0.0\",\n \"nodemon\": \"^2.0.4\",\n \"ts-node\": \"^9.0.0\",\n \"typescript\": \"^4.0.3\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nconst { PrismaClient } = require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function main() {\n  const allLinks = await prisma.link.findMany()\n  console.log(allLinks)\n}\n\nmain()\n  .catch(e => {\n    throw e\n  })\n  .finally(async () => {\n    await prisma.disconnect()\n  })\n```\n\n```text\n/usr/bin/node[20367]: ../src/node_http_parser_impl.h:529:static void node::{anonymous}::Parser::Initialize(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `args[3]->IsInt32()' failed.\n 1: 0xa17c40 node::Abort() [/usr/bin/node]\n 2: 0xa17cbe  [/usr/bin/node]\n 3: 0xa3214a  [/usr/bin/node]\n 4: 0xc019e9  [/usr/bin/node]\n 5: 0xc037d7 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [/usr/bin/node]\n 6: 0x1409319  [/usr/bin/node]\n```\n\n```text\n{\n  \"name\": \"learn\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A GraphQL Server from scratch for learning purpose.\",\n  \"main\": \"index.ts\",\n  \"scripts\": {\n    \"start\": \"dotenv -- nodemon -e ts,graphql -x ts-node src/index.ts\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"keywords\": [],\n  \"dependencies\": {\n    \"graphql-yoga\": \"^1.18.3\"\n  },\n  \"devDependencies\": {\n    \"@prisma/cli\": \"^2.8.1\",\n    \"@prisma/client\": \"^2.8.1\",\n    \"@types/node\": \"^14.11.2\",\n    \"dotenv-cli\": \"^4.0.0\",\n    \"nodemon\": \"^2.0.4\",\n    \"ts-node\": \"^9.0.0\",\n    \"typescript\": \"^4.0.3\"\n  }\n}\n```\n\n```text\nscript.ts\n```\n\n```text\nnode src/script.ts\n```\n\n```text\nts-node src/script.ts\n```\n\n```text\nscript.ts\n```\n\n```text\nnode src/script.ts\n```\n\n```text\nts-node src/script.ts\n```\n\n```text\npackage.json\n```\n\n```text\nundici\n```\n\n========================================\n\nComments:\n- I'm also running into this, deploying on heroku. 2020-10-11T05:48:46.590156+00:00 app[web.1]: /app/.heroku/node/bin/node[133]: ../src/node_http_parser_impl.h:529:static void node::{anonymous}::Parser::Initialize(const v8::FunctionCallbackInfo&): Assertion `args[3]->IsInt32()' failed. Looks like a good thing to open on their github as an issue.\n- @Mark yap, I've created an issue in nodejs repository. For now you need to downgrade your node version to `v12.18.4` or upgrading it to `v14`.\n- Yes, you're right. I've created an issue in nodejs repository and the error only show in node `v12.19.0`. For now I'm downgrading my node version to `v12.18.4` and it's work properly. Thank you for the answer.","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":188,"estimatedTokens":1164}}171{"id":"stack-70092844","source":"stackoverflow","questionId":70092844,"title":"Session undefined in client side although available in server side in NextAuth.js v4 beta","tags":["reactjs","next.js","prisma","next-auth"],"text":"Title: Session undefined in client side although available in server side in NextAuth.js v4 beta\nTags: reactjs, next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI am using `NextAuth.js v4` beta version to set up server-side rendering and add sessions via props. \n\nThe `session` data gets console-logged from the `getServerSideProps` function in the `index.js` file, however, the client-side console log result of the `session` is `undefined`.\n\nWhat could be the issue here? How can I fix this?\n\nThe `_app.js` code:\n\n```\nimport { SessionProvider } from \"next-auth/react\"\n\nexport default function MyApp({\n Component,\n pageProps: { session, ...pageProps },\n}) {\n return (\n \n \n \n )\n}\n```\n\n`[...nextauth].js` code:\n\n```\nimport NextAuth from \"next-auth\"\nimport GoogleProvider from \"next-auth/providers/google\"\nimport { PrismaAdapter } from \"@next-auth/prisma-adapter\"\nimport { PrismaClient } from \"@prisma/client\"\n\nconst prisma = new PrismaClient()\n\nexport default NextAuth({\n adapter: PrismaAdapter(prisma),\n providers: [\n GoogleProvider({\n clientId: process.env.GOOGLE_CLIENT_ID,\n clientSecret: process.env.GOOGLE_CLIENT_SECRET,\n }),\n ],\n secret: process.env.SECRET,\n})\n```\n\n`index.js` code:\n\n```\nimport Head from 'next/head'\nimport styles from '../styles/Home.module.css'\nimport { signIn, signOut, getSession } from 'next-auth/react'\n\nexport default function Home({session}) {\n return (\n \n \n Nextjs\n \n \n \n \n {!session && (\n <>\n \n Nextjs\n \n \n You're not logged in\n \n \n\n signIn(\"google\")}>Sign In\n \n )}\n {session && (\n <>\n \n Dashboard\n \n \n Signed in as {session.user.email}\n \n \n\n Sign Out\n \n )}\n \n \n )\n}\n\nexport async function getServerSideProps(ctx) {\n const session = await getSession(ctx)\n return {\n props: { session },\n }\n}]\n```\n\nHere's my `dependencies`:\n\n```\n\"@next-auth/prisma-adapter\": \"^0.5.2-next.19\",\n\"@prisma/client\": \"^3.5.0\",\n\"next\": \"12.0.4\",\n\"next-auth\": \"^4.0.0-beta.7\",\n\"react\": \"17.0.2\",\n\"react-dom\": \"17.0.2\"\n```\n\n========================================\n\nCode:\n```text\nimport { SessionProvider } from \"next-auth/react\"\n\nexport default function MyApp({\n  Component,\n  pageProps: { session, ...pageProps },\n}) {\n  return (\n    <SessionProvider session={session} refetchInterval={5 * 60}>\n      <Component {...pageProps} />\n    </SessionProvider>\n  )\n}\n```\n\n```text\nimport NextAuth from \"next-auth\"\nimport GoogleProvider from \"next-auth/providers/google\"\nimport { PrismaAdapter } from \"@next-auth/prisma-adapter\"\nimport { PrismaClient } from \"@prisma/client\"\n\nconst prisma = new PrismaClient()\n\nexport default NextAuth({\n  adapter: PrismaAdapter(prisma),\n  providers: [\n    GoogleProvider({\n      clientId: process.env.GOOGLE_CLIENT_ID,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET,\n    }),\n  ],\n  secret: process.env.SECRET,\n})\n```\n\n```text\nimport Head from 'next/head'\nimport styles from '../styles/Home.module.css'\nimport { signIn, signOut, getSession } from 'next-auth/react'\n\nexport default function Home({session}) {\n  return (\n    <div className={styles.container}>\n      <Head>\n        <title>Nextjs</title>\n        <meta name=\"description\" content=\"Nextjs\" />\n        <link rel=\"icon\" href=\"/favicon.ico\" />\n      </Head>\n      <main>\n        {!session && (\n          <>\n            <h1>\n              Nextjs\n            </h1>\n            <h2 className={styles.subheader}>\n              You're not logged in\n            </h2>\n            <br />\n            <button onClick={() => signIn(\"google\")}>Sign In</button>\n          </>\n        )}\n        {session && (\n          <>\n            <h1>\n              Dashboard\n            </h1>\n            <h2 className={styles.subheader}>\n              Signed in as {session.user.email}\n            </h2>\n            <br />\n            <button onClick={signOut}>Sign Out</button>\n          </>\n        )}\n      </main>\n    </div>\n  )\n}\n\n\nexport async function getServerSideProps(ctx) {\n  const session = await getSession(ctx)\n  return {\n    props: { session },\n  }\n}]\n```\n\n```text\n\"@next-auth/prisma-adapter\": \"^0.5.2-next.19\",\n\"@prisma/client\": \"^3.5.0\",\n\"next\": \"12.0.4\",\n\"next-auth\": \"^4.0.0-beta.7\",\n\"react\": \"17.0.2\",\n\"react-dom\": \"17.0.2\"\n```\n\n```text\nNextAuth.js v4\n```\n\n```text\nsession\n```\n\n```text\ngetServerSideProps\n```\n\n```text\nindex.js\n```\n\n```text\nsession\n```\n\n```text\nundefined\n```\n\n```text\n_app.js\n```\n\n```text\n[...nextauth].js\n```\n\n```text\nindex.js\n```\n\n```text\ndependencies\n```\n\n```text\nimport Head from 'next/head'\nimport styles from '../styles/Home.module.css'\nimport { signIn, signOut, getSession } from 'next-auth/react'\n\nexport default function Home({user}) {\n  return (\n    <div className={styles.container}>\n      <Head>\n        <title>Nextjs</title>\n        <meta name=\"description\" content=\"Nextjs\" />\n        <link rel=\"icon\" href=\"/favicon.ico\" />\n      </Head>\n      <main>\n        {!user && (\n          <>\n            <h1>\n              Nextjs\n            </h1>\n            <h2 className={styles.subheader}>\n              You're not logged in\n            </h2>\n            <br />\n            <button onClick={() => signIn(\"google\")}>Sign In</button>\n          </>\n        )}\n        {user && (\n          <>\n            <h1>\n              Dashboard\n            </h1>\n            <h2 className={styles.subheader}>\n              Signed in as {user.email}\n            </h2>\n            <br />\n            <button onClick={signOut}>Sign Out</button>\n          </>\n        )}\n      </main>\n    </div>\n  )\n}\n\n\nexport async function getServerSideProps(ctx) {\n  const session = await getSession(ctx)\n  if (!session) {\n    return {\n      props: {}\n    }\n  }\n  const { user } = session;\n  return {\n    props: { user },\n  }\n}\n```\n\n========================================\n\nComments:\n- yeah. i got exactly same issue as you. i was just trying to do a server side rendering of the page if user has no session. your workaround works but Im still wondering y is that so\n- I ran into this problem as well, but don't understand why the session object when passed in its entirety doesn't make it to the client. Is this a NextJS thing, or a next-auth thing? It also seems weird considering the docs show a direct await call in the props object, with session as the first level property. next-auth.js.org/tutorials/securing-pages-and-api-routes","metadata":{"transformedAt":"2026-08-18T18:33:14.833Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":318,"estimatedTokens":1559}}172{"id":"stack-73344053","source":"stackoverflow","questionId":73344053,"title":"Getting \"The 'mongodb' provider is not supported with this command\" Error when try to do mongoDB migrate with Prisma","tags":["mongodb","nestjs","prisma"],"text":"Title: Getting \"The 'mongodb' provider is not supported with this command\" Error when try to do mongoDB migrate with Prisma\nTags: mongodb, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm developing some simple Todo App BE using NestJS with Prisma ORM and use MongoDB as the DB. I'm using a FREE and SHARED MongoDB cluster that is hosted in MongoDB Altas cloud. Also I added `0.0.0.0/0` to the network access tab so anyone can connect to the DB.\n\n**schema.prisma** file\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Task {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n name String?\n description String?\n status TaskStatus @default(TODO)\n}\n\nenum TaskStatus {\n TODO\n INPROGRESS\n DONE\n}\n```\n\n**.env** file\n\n```\nDATABASE_URL=\"mongodb+srv://:@todoappdb.jfo3m2c.mongodb.net/?retryWrites=true&w=majority\"\n```\n\nBut when I try to run `npx prisma migrate dev --name init` command it gives following output\n\n```\nD:\\todoapp-backend>npx prisma migrate dev --name init\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\"\n\nError: The \"mongodb\" provider is not supported with this command. For more info see https://www.prisma.io/docs/concepts/database-connectors/mongodb\n 0: migration_core::state::DevDiagnostic\n at migration-engine\\core\\src\\state.rs:250\n```\n\nCan someone point me what is the problem?\n\n========================================\n\nTop Answer:\nAccording to the official documentation (https://www.prisma.io/docs/concepts/components/prisma-migrate):\n\n**Prisma Migrate:**\n\nDoes not apply for MongoDB\nInstead of migrate dev and related commands, use db push for MongoDB.\n\ni.e\n\n```\nnpx prisma db push\n```\n\n========================================\n\nCode:\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ndatasource db {\n  provider = \"mongodb\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Task {\n  id      String   @id @default(auto()) @map(\"_id\") @db.ObjectId\n  name    String?\n  description String?\n  status  TaskStatus @default(TODO)\n}\n\nenum TaskStatus {\n  TODO\n  INPROGRESS\n  DONE\n}\n```\n\n```text\nDATABASE_URL=\"mongodb+srv://<username>:<password>@todoappdb.jfo3m2c.mongodb.net/?retryWrites=true&w=majority\"\n```\n\n```text\nD:\\todoapp-backend>npx prisma migrate dev --name init\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma\\schema.prisma\nDatasource \"db\"\n\nError: The \"mongodb\" provider is not supported with this command. For more info see https://www.prisma.io/docs/concepts/database-connectors/mongodb\n   0: migration_core::state::DevDiagnostic\n             at migration-engine\\core\\src\\state.rs:250\n```\n\n```text\n0.0.0.0/0\n```\n\n```text\nnpx prisma migrate dev --name init\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nprisma migrate\n```\n\n```text\nprisma migrate\n```\n\n```bash\nnpx prisma db push\n```\n\n```text\n// Generate prisma/schema.prisma (and .env)\nnpx prisma init\n\n// Generate assets based on schema file\nnpx prisma generate \n\n// Save to the actual database server\nnpx prisma db push\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":152,"estimatedTokens":820}}173{"id":"stack-75590671","source":"stackoverflow","questionId":75590671,"title":"Mock include property in findMany with Prisma","tags":["typescript","jestjs","mocking","relationship","prisma"],"text":"Title: Mock include property in findMany with Prisma\nTags: typescript, jestjs, mocking, relationship, prisma\nSource: Stack Overflow\n\nQuestion:\nI have setup my project with TypeScript and Jest. I have a repository method that fetches all posts with their comments like so:\n\n```\nconst data = await prisma.post.findMany({ include: { comments: true } })\n```\n\nAfter that I manipulate the comments via `data.comments.map(...)`. This is where my tests fail. The errors I get tell me that `data.comments` is undefined.\n\nThis is how I mock the the `findMany` method call:\n\n```\nprismaMock.site.findMany.mockResolvedValue([\n {\n id: '1',\n title: 'mock',\n text: 'test',\n commentIDs: [],\n },\n])\n```\n\nIf I try to add `countries: []` to the mock, then TypeScript complains by saying this property is not part of the Post type.\n\nIs there a way to mock the data I get from the `include` part of the request?\n\n========================================\n\nCode:\n```text\nconst data = await prisma.post.findMany({ include: { comments: true } })\n```\n\n```text\nprismaMock.site.findMany.mockResolvedValue([\n  {\n    id: '1',\n    title: 'mock',\n    text: 'test',\n    commentIDs: [],\n  },\n])\n```\n\n```text\ndata.comments.map(...)\n```\n\n```text\ndata.comments\n```\n\n```text\nfindMany\n```\n\n```text\ncountries: []\n```\n\n```text\ninclude\n```\n\n```text\nconst mockedData = [\n  {\n    id: '1',\n    title: 'mock',\n    text: 'test',\n    commentIDs: [],\n  },\n]\n```\n\n```text\nprismaMock.post.findMany. mockResolvedValue(mockedData)\n```\n\n========================================\n\nComments:\n- I don't think this solution works. Typescript still complains about wrong mockedData type.","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":87,"estimatedTokens":407}}174{"id":"stack-71931988","source":"stackoverflow","questionId":71931988,"title":"How to define a validation regular expression pattern for a prisma model attribute type?","tags":["prisma"],"text":"Title: How to define a validation regular expression pattern for a prisma model attribute type?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nIn prisma schema, I want to define a simple model like:\n\n```\nmodel NaturalPerson {\n id String @@id \n cpf String?\n}\n```\n\nbut here is the catch: I want the attribute `cpf` to match a certain regular expression `^[0-9]{11}$`.\n\nIs it possible to define such validation?\n\n========================================\n\nTop Answer:\nI recommend you use ZenStack which is a super set of Prisma.\n\nhttps://zenstack.dev/docs/reference/zmodel-language#example-5 it offers @regex in the schema file.\n\n========================================\n\nCode:\n```text\nmodel NaturalPerson {\n    id  String @@id   \n    cpf String?\n}\n```\n\n```text\ncpf\n```\n\n```text\n^[0-9]{11}$\n```\n\n========================================\n\nComments:\n- any affiliation? /help/promotion","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":47,"estimatedTokens":220}}175{"id":"stack-65840539","source":"stackoverflow","questionId":65840539,"title":"Prisma: Query across multiple schemas in a database","tags":["node.js","graphql","prisma","prisma-graphql","prisma2"],"text":"Title: Prisma: Query across multiple schemas in a database\nTags: node.js, graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nDoes prisma support the ability to fetch data from multiple schemas from within a single database?\n\n========================================\n\nTop Answer:\nPrisma `multiSchema` is now supported as a preview feature.\n\nSee here https://www.prisma.io/docs/guides/database/multi-schema\n\nIt was introduced in version 4.3.0 https://github.com/prisma/prisma/issues/1122#issuecomment-1231773471\n\nAs the docs say you would add the preview feature...\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"multiSchema\"]\n}\n```\n\nThen in your datasource you note the schemas...\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n schemas = [\"schema1\", \"schema2\"]\n}\n```\n\nAnd finally in each model you add the `@@schema` attribute...\n\n```\nmodel User {\n id Int @id\n orders Order[]\n profile Profile?\n\n @@schema(\"schema1\")\n}\n\nmodel Order {\n id Int @id\n user User @relation(fields: [id], references: [id])\n user_id Int\n\n @@schema(\"schema2\")\n}\n```\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  previewFeatures = [\"multiSchema\"]\n}\n```\n\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n  schemas  = [\"schema1\", \"schema2\"]\n}\n```\n\n```text\nmodel User {\n  id      Int      @id\n  orders  Order[]\n  profile Profile?\n\n  @@schema(\"schema1\")\n}\n\nmodel Order {\n  id      Int  @id\n  user    User @relation(fields: [id], references: [id])\n  user_id Int\n\n  @@schema(\"schema2\")\n}\n```\n\n```text\nmultiSchema\n```\n\n```text\n@@schema\n```\n\n========================================\n\nComments:\n- Hey! What do you mean exactly with this? With \"schema\", do you mean a \"GraphQL schema\" or a \"PostgreSQL schema\" or something else?\n- the latter one. @nburk\n- Did you find a solution for using multiple Postgres schema's with Prisma? This is one thing that is preventing me from using it.\n- @Jonathan, we'd to drop Prisma just because of this limitations. I haven't checked Prisma after it, whether they support it now or not.\n- What did you end up using?\n- GraphQL with simple Sequelize in one product (that required multi-tenancy) and GraphQL and Dynamo DB using AWS SAM at another. @Jonathan","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":108,"estimatedTokens":583}}176{"id":"stack-76686377","source":"stackoverflow","questionId":76686377,"title":"Application error: a server-side exception has occurred next.js","tags":["next.js","prisma","next-auth"],"text":"Title: Application error: a server-side exception has occurred next.js\nTags: next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI tried to deploy my nextjs application to vercel. This project is built using Prisma and Nextauth. The deployement went well, however when I go the url of my project it shows this error:\nApplication error: a server-side exception has occurred (see the server logs for more information).\nThe error in my console is this `Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.`.\n\nWhen I tried the `npm run build` command it worked well locally, and the only place where it doesn't work is the vercel deployment. Any help is appreciated.\n\n========================================\n\nTop Answer:\nI may not know much about prisma env setup on a nextjs with next-auth, but I had a similar problem only without prisma in it.\n\nif your using a custom path for lets say signing in (e.g /auth/signIn), then you have to configure it to your NEXTAUTH_URL production environment variables using vercel env add\n\nWhat i did since i was using next auth with a custom sign in page, i had to setup the nextjs environment variables of NEXTAUTH_URL to match the path for the deployed vercel project as https://yoururl.vercel.app/yourbasepath\n\nThen, i also had to add a NEXTAUTH_SECRET also to my environment variables,\n\nThe last thing was to add the path on my SessionProvider component as\n\n` import { SessionProvider } from \"next-auth/react\";\n\n```\nfunction NextAuthProvider ({ children }) {\n return \n {children\n ;\n}`\n```\n\nI hope you find this helpful.\n\n========================================\n\nCode:\n```text\nError: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.\n```\n\n```text\nnpm run build\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nVercel Environment Variables\n```\n\n```text\nnext-auth\n```\n\n```text\nfunction NextAuthProvider ({ children }) {\n  return <SessionProvider basePath=\"/api/auth\">\n        {children\n     </SessionProvider>;\n}`\n```\n\n```text\nNEXTAUTH_URL\n```\n\n```text\nNEXTAUTH_SECRET\n```\n\n```text\nNEXTAUTH_URL=https://yourappname.vercel.app/\n```\n\n```text\nNEXTAUTH_SECRET=\"GM83MqlVJn/HNUZjKk+Sm9clRP5kZM8nkYlsm5+TXc4paMh1xVxfT4nUi+ck+6qq\"\n```\n\n```text\nNEXTAUTH_URL\n```\n\n```text\nDATABASE_URL\n```\n\n```text\napi\n```\n\n```text\napi\n```\n\n```text\nserver\n```\n\n========================================\n\nComments:\n- Hello, did you find any solution to this problem, I'm also stuck\n- In my case, I forgot to add \"DATABASE_URL\" to the Environment Variables under Project Settings in Vercel. That fixed it.\n- FYI: `NEXTAUTH_SECRET` and `NEXTAUTH_URL` are changed on v5. It's become `AUTH_SECRET` and `AUTH_URL`. check authjs.dev/getting-started/deployment\n- I am having a somewhat similar issue now. I created a post for it (stackoverflow.com/questions/77479823/&hellip;). Would you have an idea that I could try out?\n- Simple Solution Upload it on server and always use it as git ignore to avoid any clash\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":112,"estimatedTokens":897}}177{"id":"stack-60866714","source":"stackoverflow","questionId":60866714,"title":"How can I specify optional query filters in Prisma?","tags":["reactjs","graphql","apollo","prisma"],"text":"Title: How can I specify optional query filters in Prisma?\nTags: reactjs, graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI am building an application with React, Apollo and Prsima that allows users to filter cars by model, brand, price... I know (for example) how to filter cars by brand:\n\n```\nconst GET_CARS = gql`\n query FilterCars($brandId: ID){\n cars(where: { \n model : { brand: { id: $brandId } }\n }) {\n id\n model {\n name\n brand {\n name\n }\n horses\n }\n year\n km\n price\n ...\n }\n`;\n```\n\nAnd in the component:\n\n```\nconst CarList = (props) => {\n const { data, loading, error } = useQuery(GET_CARS, {\n variables: {\n brandId: \"exampleBrandId\"\n }\n })\n\n ...\n}\n```\n\nThe problem is, that some parameters are optional: maybe the user does not care about the brand, or the model, or the price... So then all cars should appear: If no brand is selected, cars of all brands should appear; If no price is selected, cars of all prices should appear...\n\nHow can I do that? Something like:\n\n```\nquery FilterCars($brandId: ID){\n cars(where: { \n model : { brand: { id: $brandId || all_brand_ids } }\n }) {\n ...\n }\n}\n```\n\nI have investigated a and found a possible solution, but the custom input that the post refers to is not generated in my prisma.\n\n========================================\n\nTop Answer:\nThe answer from @Toiz is feasible. However, what if the number of parameters increases so that multiple if-statements are needed?\n\nI suggest using `undefined`.\n\nAs mentioned in prisma official docs here, you can use `undefined` to optioanally exclude a field from query.\n\nFor example,\n\n```\nwhere: { \n model : { \n brand: { \n id: $brandId != null ? $brandId : undefined\n } \n }\n}\n```\n\n========================================\n\nCode:\n```text\nconst GET_CARS = gql`\n  query FilterCars($brandId: ID){\n    cars(where: {   \n        model : { brand: { id: $brandId } }\n    }) {\n        id\n        model {\n            name\n            brand {\n             name\n            }\n            horses\n        }\n        year\n        km\n        price\n        ...\n  }\n`;\n```\n\n```text\nconst CarList = (props) => {\n    const { data, loading, error } = useQuery(GET_CARS, {\n        variables: {\n            brandId: \"exampleBrandId\"\n        }\n    })\n\n    ...\n}\n```\n\n```text\nquery FilterCars($brandId: ID){\n    cars(where: {   \n        model : { brand: { id: $brandId || all_brand_ids } }\n    }) {\n    ...\n    }\n}\n```\n\n```text\ngetCars(parent, args, {prisma}, info){\n  const queryArgs ={}\n  if(args.brandId){\n     queryArgs ={\n       where: {\n         model: {\n          id: args.brandId\n       }\n      }\n    }\n  }\n\n if(args.price){\n    queryArgs={\n      ...queryArgs,\n      where: {\n      ...queryArgs.where\n      //What every you want to add\n      }\n    }\n }\n\n  return prisma.query.cars(queryArgs, info)\n}\n```\n\n```text\nconst GET_CARS = gql`\n  query FilterCars($brandId: ID){\n    cars(where: {   \n        model : { brand: { id: $brandId } }\n    }) {\n        id\n        model {\n            name\n            brand {\n             name\n            }\n            horses\n        }\n        year\n        km\n        price\n  }\n`;\n\nconst CarList = (props) => {\n    const { data, loading, error } = useQuery(GET_CARS, {\n        variables: {\n            brandId: \"exampleBrandId\"\n        }\n    })\n}\n```\n\n```text\nwhere: {   \n  model : { \n    brand: { \n      id: $brandId != null ? $brandId : undefined\n    } \n  }\n}\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Have you tried setting a default query that displays all. So when you first enter the page, is there a default selection selected, and if so, what is it?\n- Yes, @Leafyshark there is a `select` that has the default value `all` selected.\n- Oh I see, so can you not write some middleware that queries all cars and returns them?\n- I do not think this solution works. Prisma will query all cars that have a model with an id of \"exampleBrandId\", which will be 0 because no car has an id of \"exampleBrandId\"\n- @Xalsar the solution is to make \"exampleBrandId\" a variable, and thus dynamic. Then you could have a select list of options such as: \"Lamborghini\" \"Ferrari\" \"Porsche\" and finally, \"All\" which would return all... Would that work? I am thinking about it in the context of Prisma / Next / Apollo to be fair!","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":209,"estimatedTokens":1072}}178{"id":"stack-73656963","source":"stackoverflow","questionId":73656963,"title":"How to access prisma generated types?","tags":["typescript","prisma","next-auth"],"text":"Title: How to access prisma generated types?\nTags: typescript, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI am using Next.js Prisma NextAuth. I need to access the prisma generated type of one of my tables so that I can extend my NextAuth type from it.\n\nMy question is, how do you access the types of User model?\n\n```\nmodel User {\n id String @id @default(cuid())\n name String\n nickname String? @unique\n email String @unique\n emailVerified DateTime?\n image String? @db.VarChar(500)\n title String?\n description String? @db.VarChar(500)\n accounts Account[]\n sessions Session[]\n VisitedRestaurants VisitedRestaurants[]\n Reviews Reviews[]\n ReviewImages ReviewImages[]\n ReviewLikes ReviewLikes[]\n ReviewComments ReviewComments[]\n}\n```\n\n========================================\n\nCode:\n```text\nmodel User {\n  id                 String               @id @default(cuid())\n  name               String\n  nickname           String?              @unique\n  email              String               @unique\n  emailVerified      DateTime?\n  image              String?              @db.VarChar(500)\n  title              String?\n  description        String?              @db.VarChar(500)\n  accounts           Account[]\n  sessions           Session[]\n  VisitedRestaurants VisitedRestaurants[]\n  Reviews            Reviews[]\n  ReviewImages       ReviewImages[]\n  ReviewLikes        ReviewLikes[]\n  ReviewComments     ReviewComments[]\n}\n```\n\n```js\nimport type { User } from '@prisma/client'\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":370}}179{"id":"stack-68322578","source":"stackoverflow","questionId":68322578,"title":"Recent updated version of `@types/node` is creating an error. The previous version was working fine","tags":["javascript","typescript","prisma"],"text":"Title: Recent updated version of `@types/node` is creating an error. The previous version was working fine\nTags: javascript, typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm getting this error\n\n```\nerror TS2694: Namespace 'NodeJS' has no exported member 'Global'.\n4 interface CustomNodeJsGlobal extends NodeJS.Global\n```\n\nWhile running this\n\n```\nimport { PrismaClient } from \"@prisma/client\";\n\n// add prisma to the NodeJS global type\ninterface CustomNodeJsGlobal extends NodeJS.Global {\n prisma: PrismaClient;\n}\n\n// Prevent multiple instances of Prisma Client in development\ndeclare const global: CustomNodeJsGlobal;\n\nconst prisma = global.prisma || new PrismaClient();\n\nif (process.env.NODE_ENV === \"development\") global.prisma = prisma;\n\nexport default prisma;\n```\n\n**IT'S THE PROBLEM WITH `@types/node` VERSION.**\n\n--> With `\"@types/node\": \"^15.4.0\"` (i don't remember precisely but it started from 15 (15.x.x))\n\n--> The error is shown after updating to the latest version `\"@types/node\": \"^16.3.0\"`\n\n**What is the standard way to make it work with the latest version `\"@types/node\": \"^16.3.0\",` ?**\n\n========================================\n\nCode:\n```text\nerror TS2694: Namespace 'NodeJS' has no exported member 'Global'.\n4 interface CustomNodeJsGlobal extends NodeJS.Global\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\";\n\n// add prisma to the NodeJS global type\ninterface CustomNodeJsGlobal extends NodeJS.Global {\n  prisma: PrismaClient;\n}\n\n// Prevent multiple instances of Prisma Client in development\ndeclare const global: CustomNodeJsGlobal;\n\nconst prisma = global.prisma || new PrismaClient();\n\nif (process.env.NODE_ENV === \"development\") global.prisma = prisma;\n\nexport default prisma;\n```\n\n```text\n@types/node\n```\n\n```text\n\"@types/node\": \"^15.4.0\"\n```\n\n```text\n\"@types/node\": \"^16.3.0\"\n```\n\n```text\n\"@types/node\": \"^16.3.0\",\n```\n\n```ts\ndeclare global {\n  var NEW_GLOBAL: string;\n}\n```\n\n```ts\ndeclare var NEW_GLOBAL: string;\n```\n\n```ts\nimport { PrismaClient } from \"@prisma/client\";\n\ndeclare global {\n  var prisma: PrismaClient;\n}\n\nconst prisma = global.prisma || new PrismaClient();\n\nif (process.env.NODE_ENV === \"development\") global.prisma = prisma;\n\nexport default prisma;\n```\n\n```text\nnode@16\n```\n\n```text\nNodeJS.Global\n```\n\n```text\nglobalThis\n```\n\n```text\nvar\n```\n\n```text\nlet\n```\n\n```text\nconst\n```\n\n```text\nglobalThis\n```\n\n========================================\n\nComments:\n- Be sure to read the bold letter, I didn't and lost like 3 hours 😞","metadata":{"transformedAt":"2026-08-18T18:33:14.834Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":138,"estimatedTokens":621}}180{"id":"stack-78159499","source":"stackoverflow","questionId":78159499,"title":"Prisma Many to Many relationship with at least one value","tags":["javascript","database","postgresql","prisma","rdbms"],"text":"Title: Prisma Many to Many relationship with at least one value\nTags: javascript, database, postgresql, prisma, rdbms\nSource: Stack Overflow\n\nQuestion:\nI use Prisma and Postgresql for a project to store and manage recipes.\n\nI am struggling to implement a Many to Many relationship where I can constrain one side to require at least one value for the relation field.\n\nRecipes can have one or more aromas. Aromas can be included in zero or more recipes.\n\nI use an explicit relation table because I need to store additional data in it (the quantity for each aroma in a recipe).\n\nThe Recipe, Aroma and relation models are the following:\n\n```\nmodel Recipe {\n id Int @id @default(autoincrement())\n name String\n base String? @default(\"50\\/50\")\n description String? @default(\"aucune description\")\n rating Int? @default(1)\n aromas RecipeToAromas[]\n}\n\nmodel Aroma {\n id Int @id @default(autoincrement())\n name String\n brand Brand? @relation(fields: [brandId], references: [id])\n brandId Int? @default(1)\n recipes RecipeToAromas[]\n\n @@unique([name, brandId], name: \"aromaIdentifier\")\n}\n\nmodel RecipeToAromas {\n id Int @id @default(autoincrement())\n recipeId Int\n aromaId Int\n quantityMl Int\n recipe Recipe @relation(fields: [recipeId], references: [id])\n aroma Aroma @relation(fields: [aromaId], references: [id])\n}\n```\n\nI want to constrain recipes to have at least one aroma.\n\nBy definition Many to Many defines **zero** to many relationship.\n\nI thought about solving the problem with adding an additional One to Many relationship between Recipe and Aroma.\n\nThat would imply adding an additional aroma field in Recipe to store the one aroma that is required (and rename aromas field to additionalAromas to avoid confusion) :\n\n```\nmodel Recipe {\n id Int @id @default(autoincrement())\n name String\n base String? @default(\"50\\/50\")\n description String? @default(\"aucune description\")\n rating Int? @default(1)\n aromas RecipeToAromas[]\n aroma Aroma @relation(fields: [aromaId], references: [id])\n aromaId Int\n}\n```\n\nAnd adding a recipe field in Aroma as it required to establish the relation :\n\n```\nmodel Aroma {\n id Int @id @default(autoincrement())\n name String\n brand Brand? @relation(fields: [brandId], references: [id])\n brandId Int? @default(1)\n recipes RecipeToAromas[]\n recipe Recipe[]\n\n @@unique([name, brandId], name: \"aromaIdentifier\")\n}\n```\n\nBut that feels wrong as I will have duplicates : recipes and recipe fields in Aroma would store identical data.\n\n** Edit **\nI tried to solve the problem using this solution, it creats a second problem :\nEach aroma in a recipe has to be unique in this recipe (this is reflected by the compound @unique in the relational database).\n\nIf I add the One to Many relationship between Recipe and Aroma, then an aroma can be stored more than once in a recipe :\n\n```\nawait prisma.recipe.create({\n data: {\n name: \"First recipe\",\n aromaId: 1,\n aromas: {\n create: [\n { aromaId: 1, quantityMl: 2 },\n { aromaId: 2, quantityMl: 2 },\n { aromaId: 3, quantityMl: 2 },\n ],\n },\n },\n });\n```\n\nI could of course workaround the problem by just relying on validation in mutation functions and user input. And probably try to add a layer of safety with types as I am using typescript.\nBut I feel like it would make the database brittle and is prone to error especially if I have to collaborate with other devs, or even use the database in a different projet.\n\nI could not find any resource covering a similar situation, and of course I have spend a lot of time searching and re-reading the documentation.\n\nI am new to prisma (started yesterday) and I dont have too much experience with RDBMS, so it feels like I am missing something.\n\n========================================\n\nTop Answer:\nI finally found a clear answer : it has to be implemented using input check / validation.\n\n**Check the answer provided by @Ianis that solves the problem by using Triggers** (another concept I didnt know about SQL db ^^') and make the db more robust.\n\n*I think my answer is **still useful to beginners using Prisma** like me to better understand Prisma and relations in SQL dbs.*\n\nMy misunderstanding actually came from my lack of knowledge about RDBMS :\n\nIn a One-to-Many relationship, the information is actually stored only on one side.\nA Many-to-Many relationship is implemented by storing 2 One-to-Many relationships as foreign keys in a relation table.\n\n### My case as an example\n\nThere is a Many-To-Many relationship between recipes and aromas.\nHence the Recipe table structure looks like this :\n\nhttps://i.sstatic.net/zjX8o.png\n\nYou can notice there is no information about the relation.\n\nIn the same way the Aromas table looks like this :\nhttps://i.sstatic.net/N4hWu.png\n\nThe relation information is stored in the relation table (aptly named ^^') as foreign keys :\nhttps://i.sstatic.net/mm4xy.png\n\nSo using Prisma, the only solution to make a recipe have **at least one** aroma (instead of zero or more) is to check / validate the input when creating a recipe entry.\n\nThis is due to the fact that under the hood, when an aroma argument is specified in the call to the create function, Prisma actually makes a query to create a Recipe row **AND** to create a row in the relation table.\n\nI got confused because in the Prisma model the relationship appears on both side, which is not the case in the underlying database.\n\n```\nmodel Recipe {\n id Int @id @default(autoincrement())\n name String\n base String? @default(\"50\\/50\")\n description String? @default(\"aucune description\")\n rating Int? @default(1)\n aromas RecipeToAromas[] //the relation to the relation table appears here\n}\n\nmodel Aroma {\n id Int @id @default(autoincrement())\n name String\n brand Brand? @relation(fields: [brandId], references: [id])\n brandId Int? @default(1)\n recipes RecipeToAromas[] //and here\n\n @@unique([name, brandId], name: \"aromaIdentifier\")\n}\n```\n\nIt is actually stated in Prisma documentation :\n\n**Note** The relation field does not \"manifest\" in the underlying database schema. On the other side of the relation, the annotated relation field and its relation scalar field represent the side of the relation that stores the foreign key in the underlying database.\n\nI think the conclusion is : if you are a beginner like me and decide to use an ORM, **you have to make sure** that you actually understand database structures and concepts (and ideally query language) that the ORM abstracts.\n\n========================================\n\nCode:\n```text\nmodel Recipe {\n  id          Int              @id @default(autoincrement())\n  name        String\n  base        String?          @default(\"50\\/50\")\n  description String?          @default(\"aucune description\")\n  rating      Int?             @default(1)\n  aromas      RecipeToAromas[]\n}\n\nmodel Aroma {\n  id      Int              @id @default(autoincrement())\n  name    String\n  brand   Brand?           @relation(fields: [brandId], references: [id])\n  brandId Int?             @default(1)\n  recipes RecipeToAromas[]\n\n  @@unique([name, brandId], name: \"aromaIdentifier\")\n}\n\nmodel RecipeToAromas {\n  id         Int    @id @default(autoincrement())\n  recipeId   Int\n  aromaId    Int\n  quantityMl Int\n  recipe     Recipe @relation(fields: [recipeId], references: [id])\n  aroma      Aroma  @relation(fields: [aromaId], references: [id])\n}\n```\n\n```text\nmodel Recipe {\n  id          Int              @id @default(autoincrement())\n  name        String\n  base        String?          @default(\"50\\/50\")\n  description String?          @default(\"aucune description\")\n  rating      Int?             @default(1)\n  aromas      RecipeToAromas[]\n  aroma       Aroma            @relation(fields: [aromaId], references: [id])\n  aromaId     Int\n}\n```\n\n```text\nmodel Aroma {\n  id      Int              @id @default(autoincrement())\n  name    String\n  brand   Brand?           @relation(fields: [brandId], references: [id])\n  brandId Int?             @default(1)\n  recipes RecipeToAromas[]\n  recipe  Recipe[]\n\n  @@unique([name, brandId], name: \"aromaIdentifier\")\n}\n```\n\n```text\nawait prisma.recipe.create({\n    data: {\n      name: \"First recipe\",\n      aromaId: 1,\n      aromas: {\n        create: [\n          { aromaId: 1, quantityMl: 2 },\n          { aromaId: 2, quantityMl: 2 },\n          { aromaId: 3, quantityMl: 2 },\n        ],\n      },\n    },\n  });\n```\n\n```text\nCREATE OR REPLACE FUNCTION consistency_check_recipe() RETURNS TRIGGER AS $$\n  BEGIN\n    IF NOT EXISTS (SELECT * FROM RecipeToAromas WHERE recipeId = NEW.id)\n      THEN RETURN NULL;\n      ELSE RETURN NEW;\n    END IF;\n  END;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE TRIGGER recipe_aroma_minum_check\nBEFORE INSERT ON Recipe\nFOR EACH ROW EXECUTE FUNCTION consistency_check_recipe();\n```\n\n```text\nCREATE OR REPLACE FUNCTION consistency_check_recipe() RETURNS TRIGGER AS $$\n  BEGIN\n    IF NOT EXISTS (SELECT * FROM RecipeToAromas WHERE recipeId = NEW.ID) THEN\n       RAISE EXCEPTION 'Must have at least 1 Aroma';\n    END IF;\n    RETURN NULL;\n  END;\n$$ LANGUAGE plpgsql;\n\nCREATE CONSTRAINT TRIGGER recipe_aroma_check\nAFTER INSERT OR UPDATE ON Recipe\nINITIALLY DEFERRED\nFOR EACH ROW EXECUTE FUNCTION consistency_check_recipe();\n```\n\n```text\nBEGIN;\n\nINSERT INTO Recipe\nVALUES (1, 'Borsh', 'Tasty Water', 'Food Nothing more', 100);\n\nINSERT INTO RecipeToAromas\nVALUES (DEFAULT, 1, 3, 4);\n\nCOMMIT;\n```\n\n```text\nRecipe\n```\n\n```text\nRecipe\n```\n\n```text\nINSERT\n```\n\n```text\nUPDATE\n```\n\n```text\nUPDATE\n```\n\n```text\nDELETE\n```\n\n```text\nRecipeToAromas\n```\n\n```text\nmodel Recipe {\n  id          Int              @id @default(autoincrement())\n  name        String\n  base        String?          @default(\"50\\/50\")\n  description String?          @default(\"aucune description\")\n  rating      Int?             @default(1)\n  aromas      RecipeToAromas[] //the relation to the relation table appears here\n}\n\nmodel Aroma {\n  id      Int              @id @default(autoincrement())\n  name    String\n  brand   Brand?           @relation(fields: [brandId], references: [id])\n  brandId Int?             @default(1)\n  recipes RecipeToAromas[] //and here\n\n  @@unique([name, brandId], name: \"aromaIdentifier\")\n}\n```\n\n========================================\n\nComments:\n- Well, as I know there is not such a thing for databases. Maybe you can add some custom SQL to your migrations that checks the input and throws error if there is not at least 1 value when inserting the record or trying to delete all the relations. However, let's be honest, you are not gonna really use your database in multiple projects. so, it's not necessary to overthink it. Just simply add a middleware using prisma to check for the inputs for CUD operations and make sure that there is always at least one item for the records, this way you also have the freedom to change the logic in future!\n- Hi, thanks for you answer. I have to admit I am surprised as I would expect this to be a very common pattern. I guess I will rely on inputs validation for the moment and later dive deeper in SQL.\n- Thanks ! This is the solution I was looking for, even though it is not specific to Prisma. For Prisma users that got blocked by the same problem, you can check my answer below as it is probably because you are confused by how Prisma works and how relations are represented in SQL databases.\n- I am probably making a mistake as I am new to functions and triggers, but I get the following error, pointing as the first letter of \"INITIALLY\" : ERROR: syntax error at or near \"INITIALLY\" LINE 13: INITIALLY DEFERRED\n- No that was my fault sorry, forgot to put the CONSTRAINT keyword in the TRIGGER definition, I'm pretty sure there is a better way of doing this then the trigger I gave you, but I need to consult the docs, and I'm currently not at home, if you can wait like 4 hours I can give you a proper full answer. Really sorry for the midway answer\n- no problem thanks a lot for your help, the missing CONSTRAINT keyword was the problem. I guess this solution is kind of resource hungry as It executes consistency_check_recipe on each line. I am very curious about any other solution as I am learning :) thanks again","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":350,"estimatedTokens":3009}}181{"id":"stack-70834547","source":"stackoverflow","questionId":70834547,"title":"Prisma client query for latest values of each user","tags":["javascript","sql","prisma"],"text":"Title: Prisma client query for latest values of each user\nTags: javascript, sql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am new to `prisma-client` and I want to return the latest value register by each user of a given company.\n\nThis is my `schema.prisma`:\n\n```\nmodel Locations {\n id Int @id @default(autoincrement())\n user String\n company String\n latitude String\n longitude String\n timestamp String\n}\n```\n\nThis is what I have tried so far:\n\n```\nconst lastLocations = await db.locations.findMany({\n where: {\n company,\n },\n orderBy: {\n id: 'desc',\n },\n take: 1,\n });\n```\n\nBut I need to get 1 value for each user, I solved this previously in sql with:\n\n```\nWITH ranked_messages AS ( SELECT m.*, ROW_NUMBER() OVER (PARTITION BY userID ORDER BY timestamp DESC) AS rn FROM locations AS m ) SELECT * FROM ranked_messages WHERE rn = 1 AND companyID = \"${companyID}\";`;\n```\n\nBut I have no idea how to do proceed in prisma. Is there an \"each\" method?\n\nI appreciate any help. Thank you.\n\n========================================\n\nCode:\n```text\nmodel Locations {\n    id        Int    @id @default(autoincrement())\n    user      String\n    company   String\n    latitude  String\n    longitude String\n    timestamp String\n}\n```\n\n```text\nconst lastLocations = await db.locations.findMany({\n    where: {\n      company,\n    },\n    orderBy: {\n      id: 'desc',\n    },\n    take: 1,\n  });\n```\n\n```text\nWITH ranked_messages AS (   SELECT m.*, ROW_NUMBER() OVER (PARTITION BY userID ORDER BY timestamp DESC) AS rn FROM locations AS m ) SELECT * FROM ranked_messages WHERE rn = 1 AND companyID = \"${companyID}\";`;\n```\n\n```text\nprisma-client\n```\n\n```text\nschema.prisma\n```\n\n```text\nconst lastLocations = await db.locations.findMany({\n    where: {\n      company,\n    },\n    distinct: ['user'],\n    orderBy: {\n      id: 'desc',\n    },\n  });\n```\n\n```text\ndistinct\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":97,"estimatedTokens":461}}182{"id":"stack-70994534","source":"stackoverflow","questionId":70994534,"title":"Get the schema from table in prisma","tags":["database","schema","prisma"],"text":"Title: Get the schema from table in prisma\nTags: database, schema, prisma\nSource: Stack Overflow\n\nQuestion:\nI was deleted the migration folders and schema file suddenly :|\n\nIs there any way to get schema from tables in prisma?\n\n========================================\n\nCode:\n```text\nprisma db pull\n```\n\n```text\nprisma generate\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":19,"estimatedTokens":83}}183{"id":"stack-71892973","source":"stackoverflow","questionId":71892973,"title":"Prisma.io + Full Text Search + PostgreSQL: Search is only working with exact match","tags":["postgresql","full-text-search","prisma"],"text":"Title: Prisma.io + Full Text Search + PostgreSQL: Search is only working with exact match\nTags: postgresql, full-text-search, prisma\nSource: Stack Overflow\n\nQuestion:\nI have enabled full text search for prisma and I would like to search the `email` field returning all entries that match.\n\nI got the following code:\n\n```\nconst data = await this.prismaService.merchant.findMany({\n where: {\n email: {\n search: '12rwqg13tr222vqfgedvqrw22@someprovider.de',\n },\n },\n});\n```\n\nThis is working when I enter the exact email address. However, when I try to search for a part of it, i.e. `12rwqg13tr222vqfgedvqrw22@someprovider`, I get no results.\n\nDo I have to create indexes to accomplish this? In the docs it is mentioned that I only need indexes for PostgreSQL if I want to speed up the queries. Am I missing something here?\n\n========================================\n\nCode:\n```text\nconst data = await this.prismaService.merchant.findMany({\n  where: {\n    email: {\n      search: '12rwqg13tr222vqfgedvqrw22@someprovider.de',\n    },\n  },\n});\n```\n\n```text\nemail\n```\n\n```text\n12rwqg13tr222vqfgedvqrw22@someprovider\n```\n\n```text\nconst res = await prisma.post.findMany({\n  where: {\n    author: {\n      email: {\n        contains: 'prisma.io',\n      },\n    },\n  },\n})\n```\n\n```text\nconst res = await prisma.post.findMany({\n  where: {\n    author: {\n      email: {\n        contains: 'prisma.io',\n        mode: 'insensitive',\n      },\n    },\n  },\n})\n```\n\n```text\ncontains\n```\n\n```text\nPrisma.IO\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":76,"estimatedTokens":370}}184{"id":"stack-53974926","source":"stackoverflow","questionId":53974926,"title":"With Prisma, How can we add a comment for a Type?","tags":["schema","graphql","prisma","prisma-graphql"],"text":"Title: With Prisma, How can we add a comment for a Type?\nTags: schema, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nWith prisma.io (graphQl), we have:\n\n- File: `datamodel.graphql`\n\n```\n\"\"\"I am a great User\"\"\"\ntype User {\n id: ID! @unique\n email: String! @unique\n}\n```\n\nafter doing `prisma deploy`, it generates a file without the comment from the file `datamodel.graphql`\n\n- File `generated-schema.graphql`\n\n```\ntype User implements Node {\n id: ID!\n email: String!\n}\n```\n\nIn the prisma `playground`, I do not have the comment.\nhttps://i.sstatic.net/WRSbb.png\n\n**How can we add a comment for a Type in order to generate a documentation in playground?**\n\nWorkaround:\n\nIf I cheat and add a comment in the `generated-schema.graphql` (this file will be overridden after the next `prisma deploy`)\n\n`\"\"\"I am a great User\"\"\"\ntype User implements Node {\n id: ID!\n email: String!\n}`\n\nwe have: \nhttps://i.sstatic.net/A5LT4.png\n\nRelated topics:\n\nhttps://github.com/prisma/graphql-playground/issues/819\n\nhttps://www.prisma.io/forum/t/getting-prisma-comments-descriptions-to-appear-in-graphql-playground-schema/2980\n\nhttps://github.com/prisma/prisma/issues/2152\n\n========================================\n\nTop Answer:\nTools like Nexus allow for it. Optional descriptions could be included along with types and individual fields.\n\nRef to docs\n\n========================================\n\nCode:\n```text\n\"\"\"I am a great User\"\"\"\ntype User {\n  id: ID! @unique\n  email: String! @unique\n}\n```\n\n```text\ntype User implements Node {\n  id: ID!\n  email: String!\n}\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\nprisma deploy\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\ngenerated-schema.graphql\n```\n\n```text\nplayground\n```\n\n```text\ngenerated-schema.graphql\n```\n\n```text\nprisma deploy\n```\n\n```text\n\"\"\"I am a great User\"\"\"\ntype User implements Node {\n  id: ID!\n  email: String!\n}\n```\n\n```text\nCurrently, there’s no easy way to resolve this. This is an open feature request, which you can learn more about here:\n```\n\n========================================\n\nComments:\n- Looks like the links are broken or the docs moved?","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":527}}185{"id":"stack-52591611","source":"stackoverflow","questionId":52591611,"title":"Specifying Prisma's database name in postgresql","tags":["postgresql","prisma"],"text":"Title: Specifying Prisma's database name in postgresql\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement a microservice architecture where every microservice has its' own database. I'm using prisma as a data access layer between my services and a **single** database server. Since I have a single database server I want each prisma instance to access its' own database on this server, but I didn't find an option to specify name of a database used by particular prisma instance.\n\nSo here's the question. Is there a way to specify a database name for prisma instance?\n\nHere's my `docker-compose.yml` file if it's helpful:\n\n```\nversion: '3'\nservices:\n prisma:\n image: prismagraphql/prisma:1.14\n restart: always\n ports:\n - \"${PRODUCT_PRISMA_PORT}:${PRODUCT_PRISMA_PORT}\"\n environment:\n PRISMA_CONFIG: |\n port: ${PRODUCT_PRISMA_PORT}\n managementApiSecret: ${PRODUCT_PRISMA_SECRET}\n databases:\n product:\n connector: postgres\n host: postgres\n port: 5432\n user: prisma\n password: prisma\n migrations: true\n postgres:\n image: postgres:11-alpine\n restart: always\n environment:\n POSTGRES_USER: prisma\n POSTGRES_PASSWORD: prisma\n volumes:\n - /var/lib/postgresql/data\n product-app:\n command: yarn start\n image: product-web\n volumes:\n - ./product-service:/usr/app\n ports:\n - \"${PRODUCT_APP_PORT}:${PRODUCT_APP_PORT}\"\n depends_on:\n - prisma\n environment:\n PORT: ${PRODUCT_APP_PORT}\n PRISMA_ENDPOINT: ${PRODUCT_PRISMA_ENDPOINT}\n```\n\n========================================\n\nCode:\n```text\nversion: '3'\nservices:\n  prisma:\n    image: prismagraphql/prisma:1.14\n    restart: always\n    ports:\n    - \"${PRODUCT_PRISMA_PORT}:${PRODUCT_PRISMA_PORT}\"\n    environment:\n      PRISMA_CONFIG: |\n        port: ${PRODUCT_PRISMA_PORT}\n        managementApiSecret: ${PRODUCT_PRISMA_SECRET}\n        databases:\n          product:\n            connector: postgres\n            host: postgres\n            port: 5432\n            user: prisma\n            password: prisma\n            migrations: true\n  postgres:\n    image: postgres:11-alpine\n    restart: always\n    environment:\n      POSTGRES_USER: prisma\n      POSTGRES_PASSWORD: prisma\n    volumes:\n      - /var/lib/postgresql/data\n  product-app:\n    command: yarn start\n    image: product-web\n    volumes:\n      - ./product-service:/usr/app\n    ports:\n      - \"${PRODUCT_APP_PORT}:${PRODUCT_APP_PORT}\"\n    depends_on:\n      - prisma\n    environment:\n      PORT: ${PRODUCT_APP_PORT}\n      PRISMA_ENDPOINT: ${PRODUCT_PRISMA_ENDPOINT}\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nenvironment:\n  PRISMA_CONFIG: |\n    port: ${PRODUCT_PRISMA_PORT}\n    managementApiSecret: ${PRODUCT_PRISMA_SECRET}\n    databases:\n      product:\n        connector: postgres\n        host: postgres\n        port: 5432\n        user: prisma\n        password: prisma\n        migrations: true\n        database: ${DATABASE}\n```\n\n```text\npg_advisory_lock\n```\n\n```text\nObtaining exclusive agent lock... Successful.\n```\n\n```text\nObtaining exclusive agent lock...\n```\n\n========================================\n\nComments:\n- Yes, it works. Looks like the lock works only for a database, not the whole server. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":134,"estimatedTokens":783}}186{"id":"stack-70893348","source":"stackoverflow","questionId":70893348,"title":"Rollback of Prisma Interactive Transaction in NestJS not working when throwing an error","tags":["node.js","nestjs","rollback","prisma"],"text":"Title: Rollback of Prisma Interactive Transaction in NestJS not working when throwing an error\nTags: node.js, nestjs, rollback, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using the prisma ORM and NestJS and I got the following example code:\n\n```\nasync createMerchant(data: Prisma.MerchantCreateInput): Promise {\n return await this.prisma.$transaction(async (): Promise => {\n await this.prisma.merchant.create({\n data,\n });\n throw new Error(`Some error`);\n });\n}\n```\n\nI would expect that the transaction is rolled back as I have thrown an error, but it is not, it creates a new database entry.\n\nHere is the example of the official documentation.\n\nIs this maybe related to the dependency injection of NestJS and that the injected prisma service is not correctly recognizing the error? Or am I doing something wrong?\n\n========================================\n\nCode:\n```text\nasync createMerchant(data: Prisma.MerchantCreateInput): Promise<Merchant> {\n  return await this.prisma.$transaction(async (): Promise<Merchant> => {\n    await this.prisma.merchant.create({\n      data,\n    });\n    throw new Error(`Some error`);\n  });\n}\n```\n\n```text\nasync createMerchant(data: Prisma.MerchantCreateInput): Promise<Merchant> {\n  return await this.prisma.$transaction(async (prisma): Promise<Merchant> => {\n    // Not this.prisma, but prisma from argument\n    await prisma.merchant.create({\n      data,\n    });\n    throw new Error(`Some error`);\n  });\n}\n```\n\n========================================\n\nComments:\n- Can`t believe that I have not seen this! Thank you!\n- @Danila, can i call rollback method explicitly?","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":401}}187{"id":"stack-79830729","source":"stackoverflow","questionId":79830729,"title":"Prisma 7.0.1 : TypeError: Cannot read properties of undefined (reading '__internal')","tags":["node.js","typescript","prisma"],"text":"Title: Prisma 7.0.1 : TypeError: Cannot read properties of undefined (reading '__internal')\nTags: node.js, typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI was using Prisma 6, and after upgrading to Prisma 7 I had to apply some changes to my schema.prisma. These changes include modifying the schema.prisma file and adding a new prisma.config.ts file.\n\nMy current schema.prisma looks like this:\n\n```\ngenerator client {\n provider = \"prisma-client\"\n output = \"../src/generated/prisma\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n}\n```\n\nAnd my prisma.config.ts file looks like this:\n\n```\nimport \"dotenv/config\";\nimport { defineConfig, env } from \"prisma/config\";\n\nexport default defineConfig({\n schema: \"prisma/schema.prisma\",\n migrations: {\n path: \"prisma/migrations\",\n },\n datasource: {\n url: env(\"DATABASE_URL\"),\n },\n});\n```\n\nBut after adding, in this code I have this error:\n\n```\nimport { PrismaClient } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\nexport default prisma\n\n//error: \n// config = optionsArg.__internal?.configOverride?.(config) ?? config\n ^\n// TypeError: Cannot read properties of undefined (reading '__internal')\n```\n\n========================================\n\nTop Answer:\ni encountered the same problem when running **nestjs** with my **prisma** and **postgres** db running on **neon**, and i found the fix for **nestjs** (but i am sure the fix can be applied to the other frameworks)\n\ncontinuing from prisma.schema and prisma.config.ts, you should add a new prisma.service.ts file to the src folder,\n\nmake sure to have @prisma/adapter-pg installed (for postgresql only, the options for the PrismaPg adapter is different from the other adapters so do some research before)\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { PrismaClient } from './generated/prisma/client';\nimport { PrismaPg } from '@prisma/adapter-pg';\n\n@Injectable()\nexport class PrismaService extends PrismaClient {\n constructor() {\n const adapter = new PrismaPg({\n connectionString: process.env.DATABASE_URL,\n });\n super({ adapter });\n }\n}\n```\n\n, then in you database.service\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaService } from '../prisma.service';\n\n@Injectable()\nexport class DatabaseService extends PrismaService implements OnModuleInit {\n async onModuleInit() {\n await this.$connect();\n }\n}\n```\n\nthen because the prisma service uses process.env.DBURL\n\nyou have to add this to the top of the main.ts\n\n```\nimport 'dotenv/config';\n```\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client\"\n  output   = \"../src/generated/prisma\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n}\n```\n\n```text\nimport \"dotenv/config\";\nimport { defineConfig, env } from \"prisma/config\";\n\nexport default defineConfig({\n  schema: \"prisma/schema.prisma\",\n  migrations: {\n    path: \"prisma/migrations\",\n  },\n  datasource: {\n    url: env(\"DATABASE_URL\"),\n  },\n});\n```\n\n```text\nimport { PrismaClient } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\nexport default prisma\n\n//error:    \n//    config = optionsArg.__internal?.configOverride?.(config) ?? config\n                              ^\n//    TypeError: Cannot read properties of undefined (reading '__internal')\n```\n\n```js\nconst client = new PrismaClient()\n```\n\n```js\nconst client = new PrismaClient({\n  adapter: new PrismaBetterSqlite3({\n    url: 'file:./prisma/dev.db',\n  }),\n});\n```\n\n```text\nadapter\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"../generated/prisma/client\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  schemas = [\"your-schemas\"]\n}\n```\n\n```text\nmodel sku {\n  a       Int      @id @default(autoincrement())\n  b       String   @unique @map(\"b\") @db.VarChar(255)\n  c       Int?     @map(\"c\")\n  createdAt DateTime @default(now()) @map(\"created_at\") @db.Timestamp(6)\n  updatedAt DateTime @default(now()) @updatedAt @map(\"updated_at\") @db.Timestamp(6)\n\n\n  @@index([b])\n  @@map(\"c\")\n  @@schema(\"your-schemas\")\n}\n```\n\n```text\nimport { PrismaClient } from '../generated/prisma/client/index.js';\nimport { PrismaPg } from '@prisma/adapter-pg';\n\nconst globalForPrisma = globalThis;\n\n// adapter Postgres (Prisma Data Proxy / Accelerate style)\nconst adapter = new PrismaPg({\n  connectionString: process.env.DATABASE_URL\n});\n\nexport const prisma =\n  globalForPrisma.prisma ??\n  new PrismaClient({\n    adapter\n  });\n\n// simpan instance ke global supaya tidak recreate saat hot reload / nodemon\nif (process.env.NODE_ENV !== 'production') {\n  globalForPrisma.prisma = prisma;\n}\n```\n\n```text\n@schema(\"\")\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { PrismaClient } from './generated/prisma/client';\nimport { PrismaPg } from '@prisma/adapter-pg';\n\n@Injectable()\nexport class PrismaService extends PrismaClient {\n  constructor() {\n    const adapter = new PrismaPg({\n      connectionString: process.env.DATABASE_URL,\n    });\n    super({ adapter });\n  }\n}\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaService } from '../prisma.service';\n\n@Injectable()\nexport class DatabaseService extends PrismaService implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n}\n```\n\n```text\nimport 'dotenv/config';\n```\n\n========================================\n\nComments:\n- Having same issue. Normally after upgrade it was working fine then I used migration and somehow all crashed.\n- Tetap aja om gk bisa, saya coba cara ini","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":248,"estimatedTokens":1367}}188{"id":"stack-76006609","source":"stackoverflow","questionId":76006609,"title":"TS2305: Module '\"@prisma/client\"' has no exported member 'User'","tags":["typescript","nestjs","gitlab-ci","prisma"],"text":"Title: TS2305: Module '\"@prisma/client\"' has no exported member 'User'\nTags: typescript, nestjs, gitlab-ci, prisma\nSource: Stack Overflow\n\nQuestion:\nI am try to set up a Gitlab CI for a nestjs project that uses prisma. When I run the pipeline, I get this error:\nenter image description here\n\nMy .gitlab-ci.yml:\n\n```\nimage: node:latest\n\nstages:\n - build\n\nbuild:\n stage: build\n before_script:\n - corepack enable\n - corepack prepare pnpm@latest-8 --activate\n - pnpm config set store-dir .pnpm-store\n script:\n - pnpm install\n - npx prisma generate\n - pnpm run build\n cache:\n key:\n files:\n - pnpm-lock.yaml\n paths:\n - .pnpm-store\n artifacts:\n paths:\n - dist\n```\n\n`user.models.ts`:\n\n```\nimport { User } from \"@prisma/client\"; # Line that is causing the build to fail in the CI\nimport { IsEmail, IsInt, IsNotEmpty, IsString } from \"class-validator\";\n\nclass UserModel implements User {\n @IsNotEmpty()\n @IsInt()\n id: number;\n\n @IsNotEmpty()\n @IsString()\n @IsEmail()\n email: string;\n\n @IsNotEmpty()\n @IsString()\n password: string;\n}\n```\n\nRunning `pnpm run build` locally works fine.\n\nWith the following scripts I have manually looked at the output generated by prisma, and I can see that `User` is being exported as a type from `index.d.ts`.\n\n```\n- cd ./node_modules/.prisma/client\n- cat index.d.ts\n- cd ../../..\n```\n\n========================================\n\nTop Answer:\nI ran into the same error in deployment, but in my case I'm building from a Dockerfile. So for anyone coming across the same but have a different setup, the fix was to add a line high up in the Dockerfile.\n\n`COPY prisma ./`\n\nExample\n\n```\nFROM node as installer\nWORKDIR /app\nCOPY prisma ./\n...the rest of your code\n```\n\n========================================\n\nCode:\n```text\nimage: node:latest\n\nstages:\n  - build\n\nbuild:\n  stage: build\n  before_script:\n    - corepack enable\n    - corepack prepare pnpm@latest-8 --activate\n    - pnpm config set store-dir .pnpm-store\n  script:\n    - pnpm install\n    - npx prisma generate\n    - pnpm run build\n  cache:\n    key:\n      files:\n        - pnpm-lock.yaml\n    paths:\n      - .pnpm-store\n  artifacts:\n    paths:\n      - dist\n```\n\n```text\nimport { User } from \"@prisma/client\"; # Line that is causing the build to fail in the CI\nimport { IsEmail, IsInt, IsNotEmpty, IsString } from \"class-validator\";\n\nclass UserModel implements User {\n    @IsNotEmpty()\n    @IsInt()\n    id: number;\n\n    @IsNotEmpty()\n    @IsString()\n    @IsEmail()\n    email: string;\n\n    @IsNotEmpty()\n    @IsString()\n    password: string;\n}\n```\n\n```text\n- cd ./node_modules/.prisma/client\n- cat index.d.ts\n- cd ../../..\n```\n\n```text\nuser.models.ts\n```\n\n```text\npnpm run build\n```\n\n```text\nUser\n```\n\n```text\nindex.d.ts\n```\n\n```text\ngenerator client {\n  ...\n  output = \"../../node_modules/.prisma/client\"\n  ...\n}\n```\n\n```text\nFROM node as installer\nWORKDIR /app\nCOPY prisma ./\n...the rest of your code\n```\n\n```text\nCOPY prisma ./\n```\n\n```text\nimport { PrismaClient, Prisma } from '@prisma/client'\n\nconst userData: Prisma.UserCreateInput[] = ...\n```\n\n```text\nimport { UserCreateInput } from '@prisma/client'\n```\n\n```text\nnpx prisma generate\n```\n\n```text\n[npx|pnpm|npm] prisma generate\n[pnpm|npm] prisma migrate dev --name init\n```\n\n========================================\n\nComments:\n- Update: I realized that prisma generate is automatically run when doing `pnpm install` so I removed the `npx prisma generate` script and am still receiving the same error.\n- Thank you for this hint! I was checking to see if the `.prisma&#47;client` directory existed. It turned out that it didn't, so I ran `prisma generate`. This generated the necessary folder and resolved the `@prisma&#47;client` dependency.\n- This is also useful if you are in a monorepo and you need to prisma client across several repos.\n- Personally, neither option suited me. I found a solution by upgrading to the prisma v6.0.0 version.","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":202,"estimatedTokens":967}}189{"id":"stack-68840391","source":"stackoverflow","questionId":68840391,"title":"Unknown argument error when creating record","tags":["prisma","prisma2"],"text":"Title: Unknown argument error when creating record\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm encountering some interesting behaviour when using Prisma ORM. It is related to Prisma's generated types, and I've been skimming the docs trying to find out more, but there doesn't seem to be much info about generated types in there (please correct me if I'm mistaken). Here's the behaviour:\n\nSay I have a model with two 1-1 relations (`Profile` in the example below):\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n name String\n profile Profile?\n}\n\nmodel Profile {\n id Int @id @default(autoincrement())\n name String\n userId Int?\n user User? @relation(fields: [userId], references: [id])\n photoId Int?\n photo Photo? @relation(fields: [photoId], references: [id])\n}\n\nmodel Photo {\n id Int @id @default(autoincrement())\n url String\n profile Profile?\n}\n```\n\nThe following code works when creating a new profile:\n\n```\nconst user = await prisma.user.create({ data: { name: \"TestUser\" } }); \nconst profile = await prisma.profile.create({\n data: {\n name: \"TestProfile\",\n user: { connect: { id: user.id } },\n photo: { create: { url: \"http://example.com/img\" } },\n },\n});\n```\n\n... but this fails with an error:\n\n```\nconst user = await prisma.user.create({ data: { name: \"TestUser\" } });\nconst profile = await prisma.profile.create({\n data: {\n name: \"TestProfile\",\n userId: user.id,\n photo: { create: { url: \"http://example.com/img\" } },\n },\n});\n```\n\nThe error is:\n\nUnknown arg `userId` in data.userId for type ProfileCreateInput. Did you mean `user`? Available args:\n\ntype ProfileCreateInput {\n\n  name: String\n\n  user?: UserCreateNestedOneWithoutProfileInput\n\n  photo?: PhotoCreateNestedOneWithoutProfileInput\n\n}\n\nWhy is the second create-profile code invalid?\n\n========================================\n\nTop Answer:\nOn Next.js, I had to recompile things with `next dev` or `next build`. That's because the Prisma migration tool doesn't notify your on-going server.\n\n========================================\n\nCode:\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel User {\n  id      Int      @id @default(autoincrement())\n  name    String\n  profile Profile?\n}\n\nmodel Profile {\n  id      Int    @id @default(autoincrement())\n  name    String\n  userId  Int?\n  user    User?  @relation(fields: [userId], references: [id])\n  photoId Int?\n  photo   Photo? @relation(fields: [photoId], references: [id])\n}\n\nmodel Photo {\n  id      Int      @id @default(autoincrement())\n  url     String\n  profile Profile?\n}\n```\n\n```text\nconst user = await prisma.user.create({ data: { name: \"TestUser\" } });    \nconst profile = await prisma.profile.create({\n  data: {\n    name: \"TestProfile\",\n    user: { connect: { id: user.id } },\n    photo: { create: { url: \"http://example.com/img\" } },\n  },\n});\n```\n\n```text\nconst user = await prisma.user.create({ data: { name: \"TestUser\" } });\nconst profile = await prisma.profile.create({\n  data: {\n    name: \"TestProfile\",\n    userId: user.id,\n    photo: { create: { url: \"http://example.com/img\" } },\n  },\n});\n```\n\n```text\nProfile\n```\n\n```text\nuserId\n```\n\n```text\nuser\n```\n\n```js\nexport type ProfileCreateArgs = {\n  /* ... */\n  data: XOR<ProfileCreateInput, ProfileUncheckedCreateInput>;\n}\n```\n\n```js\nexport type ProfileCreateInput = {\n  id?: number;\n  /* ... */\n  user?: UserCreateNestedOneWithoutProfileInput;\n  photo?: PhotoCreateNestedOneWithoutProfileInput;\n}\n\nexport type ProfileUncheckedCreateInput = {\n  id?: number;\n  /* ... */\n  userId?: number;\n  photoId?: number;\n}\n```\n\n```text\ncreate\n```\n\n```text\nXOR\n```\n\n```text\nconnect\n```\n\n```text\ncreate\n```\n\n```text\nnext dev\n```\n\n```text\nnext build\n```\n\n```js\nconst profile = await prisma.profile.create({\n  data: {\n    name: \"TestProfile\",\n    user: { connect: { id: user.id } },\n    photo: { create: { url: \"http://example.com/img\" } },\n  },\n});\n```\n\n```text\nProfile\n```\n\n```text\nUser\n```\n\n```text\nuserId\n```\n\n```text\n{data: {..., user: {connect: {id: user.id}}}\n```\n\n```text\nuserId\n```\n\n```text\nProfile\n```\n\n```text\nuserId: user.id\n```\n\n```text\nuser: { connect: { id: user.id } }\n```\n\n========================================\n\nComments:\n- Why would they do this? 🤦‍♂️\n- There's already a great answer to the question. Why add noise?\n- This isn't noise. If the person faces the same issue and she's using Next.js, then this *adds information*.\n- If you are using a coding workflow that involves a compilation step, then *of course* you have to recompile before the changes you make to your code get reflected in the behaviour of the program. In my opinion, this has nothing to do with the question, which is why I downvoted.\n- It's not that clear. I was expecting Next.js or Prisma itself to automatically force a live reload when a migration was done. But that isn't the case.\n- This. There was a different wrong argument but it kept calling out a legit foreign key. Once the wrong argument was removed, it worked with the foreign key that was previously shown in the error.","metadata":{"transformedAt":"2026-08-18T18:33:14.835Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":255,"estimatedTokens":1296}}190{"id":"stack-73985623","source":"stackoverflow","questionId":73985623,"title":"Package files into specific folder of application bundle when deploying to AWS Lambda via Serverless Framework","tags":["aws-lambda","serverless","serverless-framework","prisma"],"text":"Title: Package files into specific folder of application bundle when deploying to AWS Lambda via Serverless Framework\nTags: aws-lambda, serverless, serverless-framework, prisma\nSource: Stack Overflow\n\nQuestion:\n### Context\n\nI am using the `aws-node-typescript` example of the Serverless Framework. My goal is to integrate Prisma into it.\n\nSo far, I have:\n\n- Created the project locally using `serverless create`\n\n- Set up a PostgreSQL database on Railway\n\n- Installed `prisma`, ran `prisma init`, created a basic `User` model and ran `prisma migrate dev` successfully\n\n- Created a second `users` function by copying the existing `hello` function\n\n- Deployed the function using `serverless deploy`\n\n- Now in my function, when I instantiate `PrismaClient`, I get an internal server error and the function logs this error: `\"ENOENT: no such file or directory, open '/var/task/src/functions/users/schema.prisma'\"`\n\nMy project structure looks as follows:\n\n```\n.\n├── README.md\n├── package-lock.json\n├── package.json\n├── prisma\n│ ├── migrations\n│ │ ├── 20221006113352_init\n│ │ │ └── migration.sql\n│ │ └── migration_lock.toml\n│ └── schema.prisma\n├── serverless.ts\n├── src\n│ ├── functions\n│ │ ├── hello\n│ │ │ ├── handler.ts\n│ │ │ ├── index.ts\n│ │ │ ├── mock.json\n│ │ │ └── schema.ts\n│ │ ├── index.ts\n│ │ └── users\n│ │ ├── handler.ts\n│ │ └── index.ts\n│ └── libs\n│ ├── api-gateway.ts\n│ ├── handler-resolver.ts\n│ └── lambda.ts\n├── tsconfig.json\n└── tsconfig.paths.json\n```\n\nAlso, here's the handler for the `users` function:\nts\n\n```\nimport { formatJSONResponse } from '@libs/api-gateway';\nimport { middyfy } from '@libs/lambda';\nimport { PrismaClient } from '@prisma/client'\n\nconst users = async (event) => {\n\n console.log(`Instantiating PrismaClient inside handler ...`)\n const prisma = new PrismaClient()\n\n return formatJSONResponse({\n message: `Hello, ${event.queryStringParameters.name || 'there'} welcome to the exciting Serverless world!`,\n event,\n });\n};\n\nexport const main = middyfy(users);\n```\n\nThe problem arises because in order to instantiate `PrismaClient`, the `schema.prisma` file needs to be part of the application bundle. Specifically, it needs to be in `/var/task/src/functions/users/` as indicated by the error message.\n\nI already adjusted the `package.patterns` option in my `serverless.ts` file to look as follows:\n\n```\npackage: { individually: true, patterns: [\"**/*.prisma\"] },\n```\n\n### Question\n\nThis way, the bundle that's uploaded to AWS Lambda includes the `prisma` directory in its root, here's the `.serverless` folder after I ran `sls package` (I've unzipped `users.zip` here so that you can see its contents):\n\n```\n.\n├── cloudformation-template-create-stack.json\n├── cloudformation-template-update-stack.json\n├── hello.zip\n├── serverless-state.json\n├── users\n│ ├── prisma\n│ │ └── schema.prisma\n│ └── src\n│ └── functions\n│ └── users\n│ ├── handler.js\n│ └── handler.js.map\n└── users.zip\n```\n\nI can also confirm that the deployed version of my AWS Lambda has the same folder structure.\n\nHow can I move the `users/prisma/schema.prisma` file into `users/src/functions/users` using the `patterns` in my `serverless.ts` file?\n\n========================================\n\nTop Answer:\nWe ran into the same issue recently. But our context is slightly different: the path to the `schema.prisma` file was `/var/task/node_modules/.prisma/client/schema.prisma`.\n\nWe solved this issue by using Serverless Package Configuration.\n\n`serverless.yml`\n\n```\nservice: 'your-service-name'\n\nplugins:\n - serverless-esbuild\n\nprovider:\n # ...\n\npackage:\n include:\n - 'node_modules/.prisma/client/schema.prisma' # This way only the `src` folder containing the lambda functions and the `node_modules` folder containing these two Prisma files were packaged and uploaded to AWS.\n\nAlthough the use of `serverless.package.include` and `serverless.package.exclude` is deprecated in favor of `serverless.package.patterns`, this was the only way to get it to work.\n\n========================================\n\nCode:\n```text\n.\n├── README.md\n├── package-lock.json\n├── package.json\n├── prisma\n│   ├── migrations\n│   │   ├── 20221006113352_init\n│   │   │   └── migration.sql\n│   │   └── migration_lock.toml\n│   └── schema.prisma\n├── serverless.ts\n├── src\n│   ├── functions\n│   │   ├── hello\n│   │   │   ├── handler.ts\n│   │   │   ├── index.ts\n│   │   │   ├── mock.json\n│   │   │   └── schema.ts\n│   │   ├── index.ts\n│   │   └── users\n│   │       ├── handler.ts\n│   │       └── index.ts\n│   └── libs\n│       ├── api-gateway.ts\n│       ├── handler-resolver.ts\n│       └── lambda.ts\n├── tsconfig.json\n└── tsconfig.paths.json\n```\n\n```text\nimport { formatJSONResponse } from '@libs/api-gateway';\nimport { middyfy } from '@libs/lambda';\nimport { PrismaClient } from '@prisma/client'\n\nconst users = async (event) => {\n\n  console.log(`Instantiating PrismaClient inside handler ...`)\n  const prisma = new PrismaClient()\n\n  return formatJSONResponse({\n    message: `Hello, ${event.queryStringParameters.name || 'there'} welcome to the exciting Serverless world!`,\n    event,\n  });\n};\n\nexport const main = middyfy(users);\n```\n\n```text\npackage: { individually: true, patterns: [\"**/*.prisma\"] },\n```\n\n```text\n.\n├── cloudformation-template-create-stack.json\n├── cloudformation-template-update-stack.json\n├── hello.zip\n├── serverless-state.json\n├── users\n│   ├── prisma\n│   │   └── schema.prisma\n│   └── src\n│       └── functions\n│           └── users\n│               ├── handler.js\n│               └── handler.js.map\n└── users.zip\n```\n\n```text\naws-node-typescript\n```\n\n```text\nserverless create\n```\n\n```text\nprisma\n```\n\n```text\nprisma init\n```\n\n```text\nUser\n```\n\n```text\nprisma migrate dev\n```\n\n```text\nusers\n```\n\n```text\nhello\n```\n\n```text\nserverless deploy\n```\n\n```text\nPrismaClient\n```\n\n```text\n\"ENOENT: no such file or directory, open '/var/task/src/functions/users/schema.prisma'\"\n```\n\n```text\nusers\n```\n\n```text\nPrismaClient\n```\n\n```text\nschema.prisma\n```\n\n```text\n/var/task/src/functions/users/\n```\n\n```text\npackage.patterns\n```\n\n```text\nserverless.ts\n```\n\n```text\nprisma\n```\n\n```text\n.serverless\n```\n\n```text\nsls package\n```\n\n```text\nusers.zip\n```\n\n```text\nusers/prisma/schema.prisma\n```\n\n```text\nusers/src/functions/users\n```\n\n```text\npatterns\n```\n\n```text\nserverless.ts\n```\n\n```text\n.\n├── README.md\n├── package-lock.json\n├── package.json\n├── prisma\n│   ├── migrations\n│   │   ├── 20221006113352_init\n│   │   │   └── migration.sql\n│   │   └── migration_lock.toml\n│   └── schema.prisma\n├── serverless.ts\n├── src\n│   ├── functions\n│   │   ├── hello\n│   │   │   ├── handler.ts\n│   │   │   ├── index.ts\n│   │   │   ├── mock.json\n│   │   │   └── schema.ts\n│   │   ├── index.ts\n│   │   └── users\n│   │       ├── schema.prisma\n│   │       ├── handler.ts\n│   │       └── index.ts\n│   └── libs\n│       ├── api-gateway.ts\n│       ├── handler-resolver.ts\n│       └── lambda.ts\n├── tsconfig.json\n└── tsconfig.paths.json\n```\n\n```text\nconst users = async (event) => {\n  console.log(`Instantiating PrismaClient inside handler ...`)\n  const prisma = new PrismaClient()\n\n  const userCount = await prisma.user.count()\n  console.log(`There are ${userCount} users in the database`)\n  return formatJSONResponse({\n    message: `Hello, ${event.queryStringParameters.name || 'there'} welcome to the exciting Serverless world!`,\n    event,\n  });\n};\n\nexport const main = middyfy(users);\n```\n\n```text\nInvalid `prisma.user.count()` invocation:\n\n\nQuery engine library for current platform \\\"rhel-openssl-1.0.x\\\" could not be found.\nYou incorrectly pinned it to rhel-openssl-1.0.x\n\nThis probably happens, because you built Prisma Client on a different platform.\n(Prisma Client looked in \\\"/var/task/src/functions/users/libquery_engine-rhel-openssl-1.0.x.so.node\\\")\n\nSearched Locations:\n\n  /var/task/.prisma/client\n  /Users/nikolasburk/prisma/talks/2022/serverless-conf-berlin/aws-node-typescript/node_modules/@prisma/client\n  /var/task/src/functions\n  /var/task/src/functions/users\n  /var/task/prisma\n  /tmp/prisma-engines\n  /var/task/src/functions/users\n  \n  \n  To solve this problem, add the platform \\\"rhel-openssl-1.0.x\\\" to the \\\"binaryTargets\\\" attribute in the \\\"generator\\\" block in the \\\"schema.prisma\\\" file:\ngenerator client {\n  provider      = \\\"prisma-client-js\\\"\n  binaryTargets = [\\\"native\\\"]\n  }\n\nThen run \\\"prisma generate\\\" for your changes to take effect.\nRead more about deploying Prisma Client: https://pris.ly/d/client-generator\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  binaryTargets = [\"native\", \"rhel-openssl-1.0.x\"]\n}\n```\n\n```text\npackage: { \n  individually: true, \n  patterns: [\"**/*.prisma\", \"**/libquery_engine-rhel-openssl-1.0.x.so.node\"],\n},\n```\n\n```text\nInvalid `prisma.user.count()` invocation:\n\n\nerror: Environment variable not found: DATABASE_URL.\n-->  schema.prisma:11\n| \n10 |   provider = \\\"postgresql\\\"\n11 |   url      = env(\\\"DATABASE_URL\\\")\n| \n\nValidation Error Count: 1\n```\n\n```text\n\"ENOENT: no such file or directory, open '/var/task/src/functions/users/schema.prisma'\"\n```\n\n```text\nschema.prisma\n```\n\n```text\nprisma\n```\n\n```text\nsrc/functions/users\n```\n\n```text\nsrc/functions/users/schema.prisma\n```\n\n```text\nprisma/schema.prisma\n```\n\n```text\nschema.prisma\n```\n\n```text\nPrismaClient\n```\n\n```text\nQuery engine library for current platform \\\"rhel-openssl-1.0.x\\\" could not be found.\n```\n\n```text\nbinaryTargets\n```\n\n```text\ngenerator\n```\n\n```text\nrhel-openssl-1.0.x\n```\n\n```text\nschema.prisma\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nnode_modules\n```\n\n```text\nschema.prisma\n```\n\n```text\nsrc/functions/users\n```\n\n```text\nnode_modules/.prisma/libquery_engine-rhel-openssl-1.0.x.so.node\n```\n\n```text\npackage.patterns\n```\n\n```text\nserverless.ts\n```\n\n```text\nEnvironment variable not found: DATABASE_URL.\n```\n\n```text\nhttps://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions/aws-node-typescript-dev-users?tab=configure\n```\n\n```text\nDATABASE_URL\n```\n\n```text\n.\n├── handlers/\n│   ├── hello.ts\n│   └── ...\n└── services/\n    ├── hello.ts\n    └── ...\n```\n\n```text\n/* eslint-disable @typescript-eslint/no-var-requires */\nconst path = require(\"path\");\n// const nodeExternals = require(\"webpack-node-externals\");\nconst CopyPlugin = require(\"copy-webpack-plugin\");\nconst slsw = require(\"serverless-webpack\");\nconst { isLocal } = slsw.lib.webpack;\n\nmodule.exports = {\n  target: \"node\",\n  stats: \"normal\",\n  entry: slsw.lib.entries,\n  // externals: [nodeExternals()],\n  mode: isLocal ? \"development\" : \"production\",\n  optimization: { concatenateModules: false },\n  resolve: { extensions: [\".js\", \".ts\"] },\n  output: {\n    libraryTarget: \"commonjs\",\n    filename: \"[name].js\",\n    path: path.resolve(__dirname, \".webpack\"),\n  },\n  module: {\n    rules: [\n      {\n        test: /\\.tsx?$/,\n        loader: \"ts-loader\",\n        exclude: /node_modules/,\n      },\n    ],\n  },\n  plugins: [\n    new CopyPlugin({\n      patterns: [\n        {\n          from: \"./prisma/schema.prisma\",\n          to: \"handlers/schema.prisma\",\n        },\n        {\n          from: \"./node_modules/.prisma/client/libquery_engine-rhel-openssl-1.0.x.so.node\",\n          to: \"handlers/libquery_engine-rhel-openssl-1.0.x.so.node\",\n        },\n      ],\n    }),\n  ],\n};\n```\n\n```text\nplugins:\n  - serverless-scriptable-plugin\n  - serverless-webpack\n\ncustom:\n  scriptable:\n    hooks:\n      before:package:createDeploymentArtifacts: npx prisma generate\n  webpack:\n    includeModules: false\n```\n\n```text\nnpm install -D webpack serverless-webpack webpack-node-externals copy-webpack-plugin serverless-scriptable-plugin\n```\n\n```text\n\"scripts\": {\n    \"test\": \"echo 'Error: no test specified' && exit 1\",\n    \"postbuild\": \"yarn fix-scrape-scheduler\",\n    \"fix-scrape-scheduler\": \"cp ../../node_modules/.prisma/client/schema.prisma .esbuild/.build/src/functions/schedule-scrapes/. && cp ../../node_modules/.prisma/client/libquery_engine-rhel-openssl-1.0.x.so.node .esbuild/.build/src/functions/schedule-scrapes/.\"\n  },\n```\n\n```text\nscripts: {\n      hooks: {\n        'before:package:createDeploymentArtifacts': 'yarn run postbuild'\n      }\n    }\n```\n\n```text\naws-nodejs-typescript\n```\n\n```text\n'serverless-plugin-scripts'\n```\n\n```text\nserverless.ts\n```\n\n```text\nplugins: ['serverless-esbuild', 'serverless-plugin-scripts'],\n```\n\n```text\npackage.json\n```\n\n```text\nserverless.ts\n```\n\n```text\n'serverless-plugin-scripts'\n```\n\n```text\npost-build\n```\n\n```text\n.build\n```\n\n```text\nlib\n```\n\n```text\nschema.prisma\n```\n\n```text\n.prisma\n```\n\n```text\nnode_modules\n```\n\n```text\nnode_modules\n```\n\n```text\nPlease make sure your database server is running at\n```\n\n```yaml\nservice: 'your-service-name'\n\nplugins:\n - serverless-esbuild\n\nprovider:\n  # ...\n\npackage:\n  include:\n    - 'node_modules/.prisma/client/schema.prisma' # <-------- this line\n    - 'node_modules/.prisma/client/libquery_engine-rhel-*'\n```\n\n```text\nschema.prisma\n```\n\n```text\n/var/task/node_modules/.prisma/client/schema.prisma\n```\n\n```text\nserverless.yml\n```\n\n```text\nsrc\n```\n\n```text\nnode_modules\n```\n\n```text\nserverless.package.include\n```\n\n```text\nserverless.package.exclude\n```\n\n```text\nserverless.package.patterns\n```\n\n========================================\n\nComments:\n- You could give `serverless-webpack-prisma` a try (prisma.io/docs/guides/deployment/deployment-guides/&hellip;).\n- The `serverless-webpack-prisma`solved my problem, thank you.\n- To solve the `Environment variable not found` problem, can consider using the serverless-dotenv-plugin to avoid manual input on `serverless.yml`\n- Thank you! This is the correct most forward way to do it :) Worked like a charm. My setup was I had my schema.prisma file in a directory for a docker image I built in order to trigger migrations from by invoking a lambda & there is no way to build a Docker image by reference the schema.prisma file if it was outside that directory where the Dockerfile lives","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":88,"totalLines":712,"estimatedTokens":3446}}191{"id":"stack-72762497","source":"stackoverflow","questionId":72762497,"title":"Query Enum type on Prisma","tags":["typescript","postgresql","enums","prisma"],"text":"Title: Query Enum type on Prisma\nTags: typescript, postgresql, enums, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to run a query on a simple prisma entity `User`.\nModel:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n name String?\n email String @unique\n role Role @default(USER)\n}\n```\n\nEntity `User` includes a prop called `Role` with a type of enum.\n`Role` enum:\n\n```\nenum Role {\n USER\n ADMIN\n}\n```\n\nExcept doing it in raw SQL query, how is this possible to do with Prisma where API:\n\n```\nconst whereNameIs = await prisma.user.findMany({\n name: 'Rich',\n role: ?\n})\n```\n\nAny custom `enum` type written in TS or conversion won't match. Is there any workaround in typescript for this?\n\n========================================\n\nCode:\n```text\nmodel User {\n  id           Int              @id @default(autoincrement())\n  name         String?\n  email        String           @unique\n  role         Role             @default(USER)\n}\n```\n\n```text\nenum Role {\n  USER\n  ADMIN\n}\n```\n\n```text\nconst whereNameIs = await prisma.user.findMany({\n  name: 'Rich',\n  role: ?\n})\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nRole\n```\n\n```text\nRole\n```\n\n```text\nenum\n```\n\n```text\nimport { Role } from '@prisma/client'\n\napp.get('users', async (req, res) => {\n  const users = await prisma.user.findMany({\n    name: 'Rich',\n    role: Role.ADMIN\n  });\n});\n```\n\n```text\nconst { role } = req.query;\n\nconst users = await prisma.user.findMany({\n  name: 'Rich',\n  role: Role[role as keyof typeof Role]\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":103,"estimatedTokens":376}}192{"id":"stack-74059232","source":"stackoverflow","questionId":74059232,"title":"Nextjs build: Property does not exist on type 'PrismaClient","tags":["typescript","next.js","netlify","prisma"],"text":"Title: Nextjs build: Property does not exist on type 'PrismaClient\nTags: typescript, next.js, netlify, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm running a NextJS app (TypeScript) with Prisma on Netlify. I recently added a new model called Trade. Here's the Prisma schema file:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel Contract {\n id Int @id @default(autoincrement())\n contractAddress String @unique\n baseUri String\n tokenName String @default(\"\")\n verified Boolean @default(false)\n}\n\nmodel Trade {\n id Int @id @default(autoincrement())\n tradeId Int @unique\n status Int\n}\n```\n\nI generated the migration file and ran the migrations in both local and production and verified the new table is present in both databases.\n\nEverything runs fine locally but when I try to deploy to Netlify, I get this error in Netlify's build log:\n\n```\nType error: Property 'trade' does not exist on type 'PrismaClient'.\n12:37:51 PM: 10 | return res.status(400).send({ message: \"No trade ID provided\" })\n12:37:51 PM: 11 | try {\n12:37:51 PM: > 12 | const tradeInDatabase = await prisma.trade.findFirst({\n```\n\nThe prisma plugin is added to the site and everything was working with other models until I added this new model. Trying to figure out why the Prisma client isn't aware of the new model in production.\n\nAny help is appreciated!\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Contract {\n  id              Int     @id @default(autoincrement())\n  contractAddress String  @unique\n  baseUri         String\n  tokenName       String  @default(\"\")\n  verified        Boolean @default(false)\n}\n\nmodel Trade {\n  id      Int @id @default(autoincrement())\n  tradeId Int @unique\n  status  Int\n}\n```\n\n```text\nType error: Property 'trade' does not exist on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.\n12:37:51 PM:   10 |     return res.status(400).send({ message: \"No trade ID provided\" })\n12:37:51 PM:   11 |   try {\n12:37:51 PM: > 12 |     const tradeInDatabase = await prisma.trade.findFirst({\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"prisma generate && next build\",\n    \"start\": \"next start\",\n    \"lint\": \"next lint\"\n  },\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":90,"estimatedTokens":605}}193{"id":"stack-68208946","source":"stackoverflow","questionId":68208946,"title":"Prisma FindMany input type","tags":["typescript","prisma"],"text":"Title: Prisma FindMany input type\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nHi I am currently using prisma 2 to query a database by using the `findMany` Method, example of how I do this is here\n\n```\nconst data = await prisma.user.findMany({\n take: 10000,\n\n select: {\n A: {\n select: {\n B: true,\n C: true,\n D: true,\n },\n },\n }\n}\n```\n\nI would like to implement it where I can define the object that this `findMany` takes externally, like\n\n```\nconst obj = {\n take: 10000,\n\n select: {\n A: {\n select: {\n B: true,\n C: true,\n D: true,\n },\n }\n }\n\nconst data = await prisma.user.findMany(obj)\n```\n\nHowever I am having an issue as to getting the type for `obj`, hovering over the `findMany` function, it tells me that the type it takes is of type `UserFindManyArgs` however I cant seem to find a way to import this.\nAny advice on how to do this will be greatly appriciated\n\n========================================\n\nCode:\n```text\nconst data = await prisma.user.findMany({\n    take: 10000,\n\n    select: {\n      A: {\n        select: {\n          B: true,\n          C: true,\n          D: true,\n        },\n      },\n    }\n}\n```\n\n```text\nconst obj = {\n    take: 10000,\n\n    select: {\n      A: {\n        select: {\n          B: true,\n          C: true,\n          D: true,\n        },\n      }\n    }\n\nconst data = await prisma.user.findMany(obj)\n```\n\n```text\nfindMany\n```\n\n```text\nfindMany\n```\n\n```text\nobj\n```\n\n```text\nfindMany\n```\n\n```text\nUserFindManyArgs\n```\n\n```text\nimport { Prisma } from '@prisma/client'\n\ntype T = Prisma.UserFindManyArgs\n```\n\n========================================\n\nComments:\n- Keep in mind that the `User` prefix is generated from the table name and the middle part `FindMany` is the type of query you want to perform. If you want to look at other types generated for your database look for the `index.d.ts` file in the `node_modules&#47;.prisma&#47;client` folder. This file contains types not only for query methods but for table rows also.","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":111,"estimatedTokens":491}}194{"id":"stack-73626300","source":"stackoverflow","questionId":73626300,"title":"How to get Prisma client to generate relationship types","tags":["javascript","node.js","typescript","postgresql","prisma"],"text":"Title: How to get Prisma client to generate relationship types\nTags: javascript, node.js, typescript, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a one-to-many relationship between a user and posts. I can create the database schema and can write / query all ok but it appears the prisma client that is being generated doesn't have the relationships on the type.\n\nFor example, my schema looks like this:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n posts Post[]\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n author User @relation(fields: [authorId], references: [id])\n authorId Int\n}\n```\n\nI then run `npx prisma generate` which creates a client with the following types\n\n```\n/**\n * Model User\n * \n */\nexport type User = {\n id: number\n}\n\n/**\n * Model Post\n * \n */\nexport type Post = {\n id: number\n authorId: number\n}\n```\n\nI would expect the user type to look like this:\n\n```\nexport type User = {\n id: number;\n posts: Post[];\n}\n```\n\nHave I defined my Prisma schema correctly? What do I need to do to get the type to include the relation?\n\n========================================\n\nCode:\n```text\nmodel User {\n  id    Int    @id @default(autoincrement())\n  posts Post[]\n}\n\nmodel Post {\n  id       Int  @id @default(autoincrement())\n  author   User @relation(fields: [authorId], references: [id])\n  authorId Int\n}\n```\n\n```js\n/**\n * Model User\n * \n */\nexport type User = {\n  id: number\n}\n\n/**\n * Model Post\n * \n */\nexport type Post = {\n  id: number\n  authorId: number\n}\n```\n\n```js\nexport type User = {\n  id: number;\n  posts: Post[];\n}\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nconst usersWithPosts = await prisma.user.findMany({\n  include: {\n    posts: true\n  }\n});\n\n// usersWithPosts has a type like this:\n// Array<User & { posts: Array<Post> }>\n```\n\n```js\ntype UserWithPosts = Prisma.UserGetPayload<{\n  include: {\n    posts: true;\n  };\n}>;\n```\n\n```text\ntype UserWithPosts = User & {\n    posts: Post[];\n}\n```\n\n```text\nUser\n```\n\n```text\nPosts\n```\n\n```text\ninclude\n```\n\n```text\nPrisma.UserGetPayload\n```\n\n```text\nGetPayload\n```\n\n========================================\n\nComments:\n- I've noticed that the `ctx.prisma.menu.findFirst` method has a return type of `(User & { posts: Post[]; })` Is the only way to combine the types manually?\n- Thanks Shea. I understand the prisma client handles the return types and how to use includes. I was wondering if Prisma generated these types that include the related field for us because it is a bit cumbersome having to manually extend the type of `User` each time\n- @Stretch0 Looks like you can leverage `Prisma.UserGetPayload` (`User` will change based on your model.) I've updated my original answer!","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":151,"estimatedTokens":673}}195{"id":"stack-73891596","source":"stackoverflow","questionId":73891596,"title":"How to delete from database where multiple conditions are met?","tags":["database","prisma"],"text":"Title: How to delete from database where multiple conditions are met?\nTags: database, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to delete a row in my database using Prisma, where I want to delete it only if two conditions are met, `slug` and `userId`.\n\nThis is what I have tried to do:\n\n```\nconst deleteComment = await prisma.favorites.delete({\n where: {\n slug: slug,\n userId: userId,\n },\n });\n```\n\nThis is my model in schema.prisma:\n\n```\nmodel Favorites {\n id Int @id @default(autoincrement())\n slug String @db.VarChar(128)\n contentType String? @db.VarChar(128)\n userId String\n user User? @relation(fields: [userId], references: [id])\n}\n```\n\nIf I remove the `userId: userId,` it deletes all rows containing the same slug, which is not ideal if multiple users have added the same slug.\n\nHow can I delete a row when both conditions are met?\n\n========================================\n\nCode:\n```js\nconst deleteComment = await prisma.favorites.delete({\n      where: {\n        slug: slug,\n        userId: userId,\n      },\n    });\n```\n\n```js\nmodel Favorites {\n  id          Int     @id @default(autoincrement())\n  slug        String  @db.VarChar(128)\n  contentType String? @db.VarChar(128)\n  userId      String\n  user        User?   @relation(fields: [userId], references: [id])\n}\n```\n\n```text\nslug\n```\n\n```text\nuserId\n```\n\n```text\nuserId: userId,\n```\n\n```js\nawait prisma.favorites.deleteMany({ where: { slug: slug, userId: userId } });\n```\n\n```text\ndeleteMany\n```\n\n```text\ndelete\n```\n\n========================================\n\nComments:\n- After removing `userId: userId`, which rows do you expect to be deleted?\n- @some-user It was just to inform you that I can delete it from the database, but I only want the row to get deleted if it can find the same userId and the slug I pass along.\n- To contribute to the answer, the output is `{count: 1}` if it deleted 1 item. And in case the `deleteMany` method name was potentially ambiguous for anyone like it was for me, it deletes only the item that matches BOTH criteria (AND operator). It DOES NOT delete many items matching any of the criteria (OR operator).","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":86,"estimatedTokens":528}}196{"id":"stack-76319880","source":"stackoverflow","questionId":76319880,"title":"TypeError: res.getHeader is not a function in NextJS API","tags":["javascript","node.js","next.js","prisma","next-auth"],"text":"Title: TypeError: res.getHeader is not a function in NextJS API\nTags: javascript, node.js, next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a web application with NextJS 13 with TypeScript, Next Auth v4, Prisma (with a SQLite database for development) and OpenAI.\n\nThe console displays an error whenever I access to the API endpoint with the following message:\n\nerror - TypeError: res.getHeader is not a function\n\nat setCookie (webpack-internal:///(sc_server)/./node_modules/next-auth/next/utils.js:11:49)\n\nI have detected that the code fails whenever it tries to assign the session variable with `getServerSession()` at this line:\n\n```\nexport async function GET(\n req: NextApiRequest, \n res: NextApiResponse\n) {\n const session = await getServerSession(req, res, authOptions) // I have been researching over the internet and I found some issues related to a Webpack middleware. But I am not using any middleware.\n\nI have tried also replacing the code to look like this:\n\n```\nexport async function GET(req: NextRequest) {\n const session = await getServerSession() // not sure how to fill this now\n const sessionErrors = checkSessionErrors(session, req.url);\n if (sessionErrors) return sessionErrors;\n\n // rest of the code\n // return stuff with NextResponse.json()\n}\n```\n\nNot sure how to proceed now, any suggested actions on this?\n\n========================================\n\nTop Answer:\nYou do not need to pass the req & res in when using the app router. it works with just the authOptions.\n\n========================================\n\nCode:\n```js\nexport async function GET(\n    req: NextApiRequest, \n    res: NextApiResponse\n) {\n    const session = await getServerSession(req, res, authOptions) // <-- here it fails\n    const sessionErrors = checkSessionErrors(session, req.url);\n    if (sessionErrors) return sessionErrors;\n\n    // rest of the code\n}\n```\n\n```js\nexport async function GET(req: NextRequest) {\n    const session = await getServerSession() // not sure how to fill this now\n    const sessionErrors = checkSessionErrors(session, req.url);\n    if (sessionErrors) return sessionErrors;\n\n    // rest of the code\n    // return stuff with NextResponse.json()\n}\n```\n\n```text\ngetServerSession()\n```\n\n```js\nexport async function POST(req: NextRequest, res: NextResponse) {\n  const session = await getServerSession(\n    req as unknown as NextApiRequest,\n    {\n      ...res,\n      getHeader: (name: string) => res.headers?.get(name),\n      setHeader: (name: string, value: string) => res.headers?.set(name, value),\n    } as unknown as NextApiResponse,\n    authOptions\n  );\n}\n```\n\n```text\ngetServerSession\n```\n\n```text\nNextApiRequest\n```\n\n```text\nNextApiResponse\n```\n\n```text\ngetHeader\n```\n\n```text\nsetHeader\n```\n\n```text\nNextResponse\n```\n\n```text\n// next: 14.0.3\n// next-auth: 4.24.5\n\n// Change the path to where your `authOptions` is\nimport { authOptions } from '@/utils/auth'\n\nimport { getServerSession } from 'next-auth'\n\nexport async function POST() {\n  const session = await getServerSession(authOptions)\n  if (!session) {\n    return Response.json({ message: 'You must be logged in.' }, { status: 401 })\n  }\n\n  try {\n    const result = someOperations() // ...\n\n    return Response.json(result)\n  } catch (err) {\n    return Response.json(err, { status: 500 })\n  }\n}\n```\n\n```text\nauthOptions\n```\n\n```text\n@/utils/auth\n```\n\n========================================\n\nComments:\n- this is not working for me can you explain the same a little more, please?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Despite its brevity, this is what worked for me.\n- Jon, can you explain your fix way in brief please?\n- You can just use `const session = await getServerSession(authOptions);`, similar to Ethan's answer","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":152,"estimatedTokens":993}}197{"id":"stack-70458934","source":"stackoverflow","questionId":70458934,"title":"Prisma Issue of managing instances of Prisma Client actively running","tags":["node.js","next.js","prisma","prisma2"],"text":"Title: Prisma Issue of managing instances of Prisma Client actively running\nTags: node.js, next.js, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm new to Prisma and Nodejs\n\nI accidentally created lots of instances of Prisma Client that keep displaying the warning of\n\n`warn(prisma-client) There are already 10 instances of Prisma Client actively running.`\n\nEven I tried to delete old files and create a new Prisma, it keep showing the same warning.\n\nI was wondering is there any way to clear the duplicated instances that already actively running?\n\nI found a lot of INFO only about to prevent the situation occur instead of clearing it.\n\n```\nNode js version. : v14.18.2\nNPM version. : 6.14.15\nprisma : 3.7.0\n@prisma/client : 3.7.0\n```\n\nThank you for your help.\n\n========================================\n\nTop Answer:\nthe problem is that you are probably creating a `new PrismaClient()`\n\nyou can use singleTon pattern to solve it ,(I'm use typescript here !)\n\n```\nimport { PrismaClient } from '@prisma/client';\n\nexport class Prisma {\n public static Prisma: PrismaClient;\n\n static getPrisma() {\n // create a new instance of PrismaClient if one isn't already created\n this.Prisma ||= new PrismaClient();\n return this.Prisma;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nNode js version.        : v14.18.2\nNPM version.            : 6.14.15\nprisma                  : 3.7.0\n@prisma/client          : 3.7.0\n```\n\n```text\nwarn(prisma-client) There are already 10 instances of Prisma Client actively running.\n```\n\n```text\nimport { PrismaClient } from \"@prisma/client\";\n\ndeclare global {\n  namespace NodeJS {\n    interface Global {\n      prisma: PrismaClient;\n    }\n  }\n}\n\nlet prisma: PrismaClient;\n\nif (!global.prisma) {\n  global.prisma = new PrismaClient({\n    log: [\"info\"],\n  });\n}\nprisma = global.prisma;\n\nexport default prisma;\n```\n\n```text\nnew PrismaClient()\n```\n\n```js\nimport { PrismaClient } from '@prisma/client';\n\nexport class Prisma {\n  public static Prisma: PrismaClient;\n\n  static getPrisma() {\n    // create a new instance of PrismaClient if one isn't already created\n    this.Prisma ||= new PrismaClient();\n    return this.Prisma;\n  }\n}\n```\n\n```text\nnew PrismaClient()\n```\n\n========================================\n\nComments:\n- For serverless all you need to do is initialize prisma outside of handler according to docs - prisma.io/docs/guides/performance-and-optimization/&hellip;\n- This is all well and good for vanilla implementations, but what is you have a new connections with different middleware ($use) and subscriptions ($on), so a new PrismaClient is required to be created each time? We use the following middleware implementations: soft-delete, createdBy/updatedBy, and RLS.","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":111,"estimatedTokens":680}}198{"id":"stack-69224864","source":"stackoverflow","questionId":69224864,"title":"Polymorphism in Prisma Schema - Best practices?","tags":["graphql","nexus","prisma","prisma-graphql","nexus-prisma"],"text":"Title: Polymorphism in Prisma Schema - Best practices?\nTags: graphql, nexus, prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nThis is more a design question than a coding question. Suppose the following schema:\n\n```\n// schema.prisma\n// Solution 1\n\nmodel Entity {\n id Int @id @default(autoincrement())\n attrs EntityAttr[] \n}\n\nmodel EntityAttr {\n id Int @id @default(autoincrement())\n value Json // or String, doesnt matter much here\n // the point is I need to attach info on the\n // join table of this relation\n attr Attr @relation(fields: [attrId], references: [id])\n entity Entity @relation(fields: [entityId], references: [id])\n\n entityId Int\n attrId Int\n\n @@unique([entityId, attrId])\n}\n\nmodel Attr {\n id Int @id @default(autoincrement())\n entities EntityAttr[] \n}\n```\n\n```\n// Solution 2\nmodel Entity {\n id Int @id @default(autoincrement())\n dateAttrs DateAttr[]\n recordAttrs RecordAttr[]\n // ... this pattern could continue for more Attr-like models\n}\n\nmodel DateAttr {\n id Int @id @default(autoincrement())\n name String\n entity Entity @relation(fields: [entityId], references: [id])\n value DateTime // Stronger typing in generated code\n}\n\nmodel RecordAttr {\n // ... define another Entity @relation(...)\n name String\n value String\n // ...\n}\n\n// ... and so on\n```\n\n`Please note that the schema might not be 100% complete or accurate. It is mainly to get the point across.`\n\nSolution 1 has its merits where redundancy and the number of tables in the database is reduced significantly (depending on the number of `Attr`s). Its downfall comes as confusing queries`*`, possible case-specific type casting and no code-completion for the `value` field for each `Attr`-like model.\n\n`*` by confusing, I mean that the option for simplified m-n queries in `prisma` is functionally disabled when using a custom join table (e.g. `EntityAttr`)\n\nSolution 2 has its merits where the generated code results in more strongly typed code generation for the `value` field, however it falls in the number of generated tables (I don't actually know if more tables is a good thing or a bad thing, all I think is that if you have similar values, they ought to be in the same table).\n\n**What would you do in my shoes?**\n\n========================================\n\nTop Answer:\nSometimes the use case can't be generalized to abstract and have a typing's.\n\nif you control them and has a limited attribute sure you can create each attribute as a separate table each has it is own schema.\n\nSome Times more freedom is needed or the blocks are dynamic.\n\nUse Case: Build A Block Document Editor Like 'notion.so' and you want to let the user create custom blocks or configure them.\n\nyou can do it like :\n\n```\nmodel Document {\n id String @id\n blocks Block[]\n}\n\nmodel Block {\n id String @id\n value Json\n index Int\n customConfig Json?\n document Document? @relation(fields: [documentID], references: [id])\n documentID String?\n blockType BlockType @relation(fields: [blockTypeID], references: [id])\n blockTypeID String\n}\n\nmodel BlockType {\n id String @id\n name String\n config Json\n blocks Block[]\n}\n```\n\nwhere config and custom config can contains html,custom css classes, link attribute color or anything.\n\nusing type script you can create block.types.ts and add different let say templates for the config's .\n\nI hope that I was useful to you, To sum it, it depends on the requirements :>)\n\n========================================\n\nCode:\n```text\n// schema.prisma\n// Solution 1\n\nmodel Entity {\n  id    Int          @id @default(autoincrement())\n  attrs EntityAttr[] \n}\n\nmodel EntityAttr {\n  id       Int         @id @default(autoincrement())\n  value    Json        // or String, doesnt matter much here\n                       // the point is I need to attach info on the\n                       // join table of this relation\n  attr     Attr        @relation(fields: [attrId], references: [id])\n  entity   Entity      @relation(fields: [entityId], references: [id])\n\n  entityId Int\n  attrId   Int\n\n  @@unique([entityId, attrId])\n}\n\nmodel Attr {\n  id       Int          @id @default(autoincrement())\n  entities EntityAttr[]   \n}\n```\n\n```text\n// Solution 2\nmodel Entity {\n  id          Int          @id @default(autoincrement())\n  dateAttrs   DateAttr[]\n  recordAttrs RecordAttr[]\n  // ... this pattern could continue for more Attr-like models\n}\n\nmodel DateAttr {\n  id     Int       @id @default(autoincrement())\n  name   String\n  entity Entity    @relation(fields: [entityId], references: [id])\n  value  DateTime  // Stronger typing in generated code\n}\n\nmodel RecordAttr {\n  // ... define another Entity @relation(...)\n  name   String\n  value  String\n  // ...\n}\n\n// ... and so on\n```\n\n```text\nPlease note that the schema might not be 100% complete or accurate. It is mainly to get the point across.\n```\n\n```text\nAttr\n```\n\n```text\n*\n```\n\n```text\nvalue\n```\n\n```text\nAttr\n```\n\n```text\n*\n```\n\n```text\nprisma\n```\n\n```text\nEntityAttr\n```\n\n```text\nvalue\n```\n\n```text\nmodel Photo {\n  id Int @id @default(autoincrement())\n\n  likes Like[] @relation(\"PhotoLike\")\n}\n\nmodel Video {\n  id Int @id @default(autoincrement())\n\n  likes Like[] @relation(\"VideoLike\")\n}\n\nenum LikableType {\n  Photo\n  Video\n}\n\nmodel Like {\n  id Int @id @default(autoincrement())\n\n  Photo Photo? @relation(\"PhotoLike\", fields: [likableId], references: [id], map: \"photo_likableId\")\n  Video Video? @relation(\"VideoLike\", fields: [likableId], references: [id], map: \"video_likableId\")\n\n  likableId   Int\n  likableType LikableType\n}\n```\n\n```text\nprisma\n```\n\n```text\npolymorphism\n```\n\n```text\nmodel Document {\n    id     String  @id\n    blocks Block[]\n}\n\nmodel Block {\n    id           String    @id\n    value        Json\n    index        Int\n    customConfig Json?\n    document     Document? @relation(fields: [documentID], references: [id])\n    documentID   String?\n    blockType    BlockType @relation(fields: [blockTypeID], references: [id])\n    blockTypeID  String\n}\n\nmodel BlockType {\n    id     String  @id\n    name   String\n    config Json\n    blocks Block[]\n}\n```\n\n```text\nmodel Obj{\n  id      String  @default(cuid())\n  objType ObjType\n  user  User?\n  publisher  Publisher?\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n  subscribers   Subscription[]\n  @@id([id,objType])\n}\n\nenum ObjType{\n  Publisher\n  User\n}\nmodel User {\n  id       String @id\n  objType  ObjType @default(User)\n  obj Obj? @relation(fields: [id,objType],references: [id,objType],map:\"UserObj\")\n  email     String   @unique\n  phone     String   @unique\n  otp   String\n  refreshToken  String\n  password  String\n  // posts     Post[]\n  roles      Role[]\n  subscriptions Subscription[] @relation(\"subscriber\")\n\n  @@unique([id,objType])\n}\n\nmodel Publisher {\n  id       String @id\n  objType  ObjType @default(User)\n  obj Obj? @relation(fields: [id,objType],references: [id,objType],map:\"PublisherObj\")\n  name     String\n  @@unique([id,objType])\n}\n\n//subscription\nmodel Subscription {\n  subscriber  User @relation(\"subscriber\",fields: [subscriberId], references: [id])\n  subscriberId  String\n  subscribed Obj @relation(fields: [subscribedId,subscribedType],references: [id,objType])\n  subscribedId   String\n  subscribedType ObjType\n  duration Int\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n  @@id([subscriberId,subscribedId,subscribedType])\n}\n```\n\n```text\nmodel User {\n    id Int @id @default(autoincrement())\n    contents Content[]\n}\n    \nmodel Content {\n    id Int @id @default(autoincrement())\n    published Boolean @default(false)\n    owner User @relation(fields: [ownerId], references: [id])\n    ownerId Int\n    contentType String\n    \n    @@delegate(contentType)\n}\n\nmodel Post extends Content {\n    title String\n}\n\nmodel Video extends Content {\n    name String\n    duration Int\n}\n```\n\n========================================\n\nComments:\n- Hi, You need to tell us about your use case to suggest the better way, there are more approaches than you mentioned.\n- I am getting Foreign key constraint failed on the field: `photo_likableId (index)` ----- if I pass likableId for video and I am getting Foreign key constraint failed on the field: `video_likableId (index)` if I pass likableId for photo.. Dit it worked on the insert operation?\n- thanks for your answer, suppose I have a subscription table that makes users related to the user and publisher table, how does Prisma distinguish subscriber users from the subscribed user in the user table?\n- as mr x says it does not work because of foreign key constraint failed\n- It works only if the `likeableId` provided on insert can be found both in the Photo and the Video tables. For example, if you provide `10` as `likeableId` and there is an Event with id `10` and a Video with id `10`, it works.\n- What does the `map:\"UserObj\"` do?\n- it is not needed. (map is required when you have multiple relation between same models)\n- Do you have any idea if there is a variation to this solution for MSSQL databases? Enums don't work in MSSQL\n- it is just metadata and is not needed. you can do it with a string or a relation to some external table that stores all your types. By the way, this type of polymorphism has some extra cost in the query and command and you should avoid using it in unnecessary situations.\n- it is better to have multiple subscription tables (or if it is needed a baseSubscription table and two separate PublisherSubscription and UserSubscription tables inherit from baseSubscription table) it is better design. (simpler and cleaner)","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":365,"estimatedTokens":2366}}199{"id":"stack-70116616","source":"stackoverflow","questionId":70116616,"title":"Next js with Prisma: Upsert based on two conditions","tags":["reactjs","postgresql","next.js","prisma"],"text":"Title: Next js with Prisma: Upsert based on two conditions\nTags: reactjs, postgresql, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do the following using Prisma:\n\nIf a category row with the same hash and user_id I have exists, just update it's \"name\" field, otherwise, create the row\n\nIs this possible? TS is giving me an error saying that the type of the key given on \"where\" has to be of `categoriesWhereUniqueInput`, yet neither hash nor user_id are unique, they can repeat, it's the combination between the two that's gonna be unique\n\nHow can I work around this? Do I have to manually check if there's an id and update/create based on that?\n\nThanks a lot in advance!\n\n```\nconst category = await prisma.categories.upsert({\n where: {\n hash,\n user_id: id,\n },\n update: {\n name,\n },\n create: {\n hash,\n name,\n user_id: id,\n },\n });\n```\n\n========================================\n\nTop Answer:\nJust in case someone stumbles upon this: if you cannot find the option in the `where` clause to select by `user_id_hash`, then you need to first have declared the unique composite constraint in the table definition.\n\n```\n@@unique([fieldOne, fieldTwo])\n```\n\nAfter doing this you will be able to select in code, on the `where` condition: `fieldOne_fieldTwo`.\n\n========================================\n\nCode:\n```js\nconst category = await prisma.categories.upsert({\n    where: {\n      hash,\n      user_id: id,\n    },\n    update: {\n      name,\n    },\n    create: {\n      hash,\n      name,\n      user_id: id,\n    },\n  });\n```\n\n```text\ncategoriesWhereUniqueInput\n```\n\n```js\nconst category = await prisma.categories.upsert({\n    where: {\n        user_id_hash: {  // user_id_hash is the type generated by Prisma. Might be called something else though. \n            user_id: 1,\n            hash: \"foo\"\n        }\n    },\n    update: {\n        name: \"bar\",\n    },\n    create: {\n        hash: \"foo\",\n        name: \"bar\",\n        user_id: 1,\n    },\n})\n```\n\n```text\nwhere\n```\n\n```text\n_\n```\n\n```text\ncategoriesWhereUniqueInput\n```\n\n```text\nuser_id_hash\n```\n\n```text\nhash_user_id\n```\n\n```text\n@@unique([fieldOne, fieldTwo])\n```\n\n```text\nwhere\n```\n\n```text\nuser_id_hash\n```\n\n```text\nwhere\n```\n\n```text\nfieldOne_fieldTwo\n```\n\n========================================\n\nComments:\n- Is there an updated answer? This does not seem to work with prisma v3.\n- Hey @j_d could you your schema and the query you want to achieve? It should still work to the best of my knowledge. (perhaps create a new question and link it here)\n- I have a table of bank accounts. I want to upsert a bank account by ID, where update only occurs if the ID matches, and also the userId field matches, otherwise create new. The answer given above does not work.\n- It's hard to tell what is wrong without looking at the schema. Could you please create a post on stackoverflow or prisma discussions with the schema and the query you have tried? @j_d\n- I haven't \"tried\" any schema, as literally everything except a single unique column query fails as per the TypeScript types. Feel free to give a dummy example if you are aware of something I'm not.","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":134,"estimatedTokens":777}}200{"id":"stack-56106736","source":"stackoverflow","questionId":56106736,"title":"Error: Valid values for the strategy argument of `@scalarList` are: RELATION","tags":["graphql","prisma","prisma-graphql"],"text":"Title: Error: Valid values for the strategy argument of `@scalarList` are: RELATION\nTags: graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nProgram pops up this -> (Valid values for the strategy argument of `@scalarList` are: RELATION.) after run prisma deploy. Any one knows why ? \n\n```\ntype User {\n id: ID! @id\n name: String!\n email: String! @unique\n password: String!\n age: Int\n img: String\n location: Location\n hostedEvents: [Event]! @relation(name: \"HostedEvents\", onDelete: CASCADE)\n joinedEvents: [Event]! @relation(name: \"EventMembers\", onDelete: CASCADE)\n pushNotificationTokens: [PushNotificationTokens]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```\n\n```\ntype Event {\n id: ID! @id\n owner: User! @relation(name: \"HostedEvents\")\n name: String!\n imgs: [String]!\n description: String\n start: DateTime!\n end: DateTime!\n categories: [Category]!\n members: [User]! @relation(name: \"EventMembers\")\n chatRoom: GroupChatRoom!\n pendingRequests: [PendingRequest]!\n locations: [Location]!\n comments: [Comment]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```\n\n========================================\n\nCode:\n```text\ntype User {\n  id: ID! @id\n  name: String!\n  email: String! @unique\n  password: String!\n  age: Int\n  img: String\n  location: Location\n  hostedEvents: [Event]! @relation(name: \"HostedEvents\", onDelete: CASCADE)\n  joinedEvents: [Event]! @relation(name: \"EventMembers\", onDelete: CASCADE)\n  pushNotificationTokens: [PushNotificationTokens]!\n  createdAt: DateTime! @createdAt\n  updatedAt: DateTime! @updatedAt\n}\n```\n\n```text\ntype Event {\n  id: ID! @id\n  owner: User! @relation(name: \"HostedEvents\")\n  name: String!\n  imgs: [String]!\n  description: String\n  start: DateTime!\n  end: DateTime!\n  categories: [Category]!\n  members: [User]! @relation(name: \"EventMembers\")\n  chatRoom: GroupChatRoom!\n  pendingRequests: [PendingRequest]!\n  locations: [Location]!\n  comments: [Comment]!\n  createdAt: DateTime! @createdAt\n  updatedAt: DateTime! @updatedAt\n}\n```\n\n```text\n@scalarList\n```\n\n```text\ntype Event {\n  id: ID! @id\n  owner: User! @relation(name: \"HostedEvents\")\n  name: String!\n  imgs: [String!]! @scalarList(strategy: RELATION)\n  description: String\n  start: DateTime!\n  end: DateTime!\n  categories: [Category]!\n  members: [User]! @relation(name: \"EventMembers\")\n  chatRoom: GroupChatRoom!\n  pendingRequests: [PendingRequest]!\n  locations: [Location]!\n  comments: [Comment]!\n  createdAt: DateTime! @createdAt\n  updatedAt: DateTime! @updatedAt\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":631}}201{"id":"stack-64438621","source":"stackoverflow","questionId":64438621,"title":"How do you filter for records which have no related records using Prisma?","tags":["prisma"],"text":"Title: How do you filter for records which have no related records using Prisma?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nUsing the schema from the Prisma docs as an example, I want to query `Users` for any users which do not have any `posts`. I can hack it like this, so that it retrieves every user where none of the posts have an ID greater than 0, but it's not very elegant. Is there a better way to do this?\n\n```\nconst result = await prisma.user.findMany({\n where: {\n post: {\n none: {\n id: { gt: 0 }\n }\n }\n }\n})\n```\n\n========================================\n\nCode:\n```js\nconst result = await prisma.user.findMany({\n  where: {\n    post: {\n      none: {\n        id: { gt: 0 }\n      }\n    }\n  }\n})\n```\n\n```text\nUsers\n```\n\n```text\nposts\n```\n\n```text\nprisma.user.findMany({ where: {\n  posts: { none: {} }\n}})\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.836Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":205}}202{"id":"stack-71190942","source":"stackoverflow","questionId":71190942,"title":"Prisma - How to point two fields to same model?","tags":["prisma"],"text":"Title: Prisma - How to point two fields to same model?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble conceptualizing how to handle this issue. I've pored through the Prisma docs and other SO questions, but they all seem to be slightly different from this situation.\n\nI have two models:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n firstName String? @map(\"first_name\")\n lastName String? @map(\"last_name\")\n email String @unique\n password String\n role UserRole @default(value: USER)\n image String? @map(\"image\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n friends Friend[]\n\n @@map(\"users\")\n}\n\nmodel Friend {\n id Int @id @default(autoincrement())\n inviteSentOn DateTime @map(\"invite_sent_on\") @db.Timestamptz(1)\n inviteAcceptedOn DateTime @map(\"invite_accepted_on\") @db.Timestamptz(1)\n userId Int @map(\"user_id\")\n friendId Int @map(\"friend_id\")\n createdAt DateTime @default(now()) @map(\"created_at\")\n updatedAt DateTime @updatedAt @map(\"updated_at\")\n\n user User @relation(fields: [userId], references: [id])\n // friend User? @relation(name: \"FriendFriend\", fields: [friendId], references: [id])\n\n @@map(\"friends\")\n}\n```\n\nI want to be able to set up the relationships on the Friend model to both point towards the User model, however I receive errors such as `Error validating field 'friend' in model 'Friend': The relation field 'friend' on Model 'Friend' is missing an opposite relation field on the model 'User'.`\n\nI've tried adding the name property to the @relation field, but start receiving errors about ambiguous relations being detected.\n\nHow do I go about setting these relations up correctly?\n\n========================================\n\nCode:\n```prisma\nmodel User {\n  id                Int               @id @default(autoincrement())\n  firstName         String?           @map(\"first_name\")\n  lastName          String?           @map(\"last_name\")\n  email             String            @unique\n  password          String\n  role              UserRole          @default(value: USER)\n  image             String?           @map(\"image\")\n  createdAt         DateTime          @default(now()) @map(\"created_at\")\n  updatedAt         DateTime          @updatedAt @map(\"updated_at\")\n\n  friends       Friend[]\n\n  @@map(\"users\")\n}\n\nmodel Friend {\n  id               Int      @id @default(autoincrement())\n  inviteSentOn     DateTime @map(\"invite_sent_on\") @db.Timestamptz(1)\n  inviteAcceptedOn DateTime @map(\"invite_accepted_on\") @db.Timestamptz(1)\n  userId           Int      @map(\"user_id\")\n  friendId         Int      @map(\"friend_id\")\n  createdAt        DateTime @default(now()) @map(\"created_at\")\n  updatedAt        DateTime @updatedAt @map(\"updated_at\")\n\n  user User @relation(fields: [userId], references: [id])\n  // friend User? @relation(name: \"FriendFriend\", fields: [friendId], references: [id])\n\n  @@map(\"friends\")\n}\n```\n\n```text\nError validating field 'friend' in model 'Friend': The relation field 'friend' on Model 'Friend' is missing an opposite relation field on the model 'User'.\n```\n\n```text\nmodel User {\n  id Int @id @default(autoincrement())\n  friend Friend? \n  friends Friend[] @relation(name: \"friends\")\n}\n\nmodel Friend {\n  id       Int @id @default(autoincrement())\n  userId   Int\n  friendId Int\n  user User @relation(fields: [userId], references: [id])\n  friend User @relation(fields: [friendId], references: [id], name: \"friends\")\n}\n```\n\n```text\nname\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":867}}203{"id":"stack-71471771","source":"stackoverflow","questionId":71471771,"title":"How to import a schema.prisma file inside another?","tags":["prisma"],"text":"Title: How to import a schema.prisma file inside another?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nOne of my schema.prisma's file is wrote like this:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./generated/own_database\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel Employee {\n ...\n}\n```\n\nAnd I have another one, which is like this:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"./generated/another_database\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL_2\")\n}\n\nmodel Costs {\n cod_center_cost Int @id\n description String? @db.VarChar(100)\n status Boolean?\n classification Int?\n}\n\n...\n```\n\nI have a model that needs to have a relation to another model, but how can I refer an another file's model?\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"./generated/own_database\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Employee {\n  ...\n}\n```\n\n```text\ngenerator client {\n    provider = \"prisma-client-js\"\n    output   = \"./generated/another_database\"\n}\n\ndatasource db {\n    provider = \"postgresql\"\n    url      = env(\"DATABASE_URL_2\")\n}\n\nmodel Costs {\n    cod_center_cost Int      @id\n    description String?  @db.VarChar(100)\n    status           Boolean?\n    classification Int?\n}\n\n...\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":87,"estimatedTokens":352}}204{"id":"stack-51334907","source":"stackoverflow","questionId":51334907,"title":"Prisma Deploy Docker error \"Could not connect to server\"","tags":["docker","graphql","prisma"],"text":"Title: Prisma Deploy Docker error \"Could not connect to server\"\nTags: docker, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nThis is steps I have done\n\n```\nprisma init\n```\n\nI set postgresql for database in my local(not exist).\n\nIt created 3 files, datamodel.graphql, docker-compose.yml, prisma.yml\n\n```\ndocker-compose up -d\n```\n\nI confirmed it running successfully \nhttps://i.sstatic.net/NajDB.png\nBut if I call `prisma deploy`, it shows me error\n\n```\nCould not connect to server at http://localhost:4466. Please check if your server is running.\n```\n\nAll I have done is standard operation described in manual and there is no customization in\nhttps://www.prisma.io/docs/tutorials/deploy-prisma-servers/local-(docker)-meemaesh3k\n\nAnd this is docker-compose.yml\n\n```\nversion: '3'\nservices:\n prisma:\n image: prismagraphql/prisma:1.11\n restart: always\n ports:\n - \"4466:4466\"\n environment:\n PRISMA_CONFIG: |\n port: 4466\n # uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security\n # managementApiSecret: my-secret\n databases:\n default:\n connector: postgres\n host: localhost\n port: '5432'\n database: databasename\n schema: public\n user: postgres\n password: root\n migrations: true\n```\n\nWhat am I missing?\n\n========================================\n\nTop Answer:\nI found this solution to the same problem i was facing\n\n```\ndocker-machine ip default\n```\n\nUse this address and replace the \"localhost\" with the IP with the above command to look something like this in prisma.yml file\n\n```\nendpoint: http://1xx.1xx.xx.xxx:4466\n```\n\nThe answer is referred from this Github Link\n\n========================================\n\nCode:\n```text\nprisma init\n```\n\n```text\ndocker-compose up -d\n```\n\n```text\nCould not connect to server at http://localhost:4466. Please check if your server is running.\n```\n\n```text\nversion: '3'\nservices:\n  prisma:\n    image: prismagraphql/prisma:1.11\n    restart: always\n    ports:\n    - \"4466:4466\"\n    environment:\n      PRISMA_CONFIG: |\n        port: 4466\n        # uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security\n        # managementApiSecret: my-secret\n        databases:\n          default:\n            connector: postgres\n            host: localhost\n            port: '5432'\n            database: databasename\n            schema: public\n            user: postgres\n            password: root\n            migrations: true\n```\n\n```text\nprisma deploy\n```\n\n```text\ndocker ps\n```\n\n```text\n$ docker ps\nCONTAINER ID        IMAGE                               COMMAND                  CREATED             STATUS              PORTS                    NAMES\n2b799c529e73        prismagraphql/prisma:1.7            \"/bin/sh -c /app/sta…\"   17 hours ago        Up 7 hours          0.0.0.0:4466->4466/tcp   myapp_prisma_1\n757dfba212f7        mysql:5.7                           \"docker-entrypoint.s…\"   17 hours ago\n```\n\n```text\ndocker-compose logs\n```\n\n```text\ndocker-machine ip default\n```\n\n```text\nendpoint: http://1xx.1xx.xx.xxx:4466\n```\n\n```text\ndocker-compose up\n```\n\n```text\ndocker run --name <ENTER_NAME> -e POSTGRES_PASSWORD=<ENTER_PASSWORD> -d -p 5433:5432 postgres\n```\n\n========================================\n\nComments:\n- Thanks, I am running postgresql in my local, in this case how to set prisma to use hosted server's local database?\n- @NomuraNori Considering prisma is isolated in container, I am not sure it would be able to access a service (like postgresql) running on the local host.\n- I get this output: \"Docker machine \"default\" does not exist. Use \"docker-machine ls\" to list machines. Use \"docker-machine create\" to add a new one.\" How to create a docker-machine?\n- @kwoxer try this command: `docker-machine create default`. You can read more here: docs.docker.com/machine/get-started\n- I'm now using mongo as docker service. So my issue is now gone.\n- Said process worked for me. The only difference was I had to run `docker-machine ls` to get the ip.","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":160,"estimatedTokens":1001}}205{"id":"stack-75990395","source":"stackoverflow","questionId":75990395,"title":"How to fix a Prisma LinkAccountError 'The provided value for the column is too long for the column's type.'","tags":["oauth-2.0","oauth","google-oauth","prisma","next-auth"],"text":"Title: How to fix a Prisma LinkAccountError 'The provided value for the column is too long for the column's type.'\nTags: oauth-2.0, oauth, google-oauth, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI got an error using Next Auth with Prisma Adapter on create-t3-app. I successfully added data on my Planetscale database.\n\nI got this error when I try to log in using Next Auth **Google Provider**. There is also **Discord Provider** which I can log in and create an account as well as a User linked to the account. I cannot create an account using Google due to the error below.\n\n```\nprisma:query BEGIN\nprisma:query INSERT INTO `foo`.`Account` (`id`,`userId`,`type`,`provider`,`providerAccountId`,`access_token`,`expires_at`,`token_type`,`scope`,`id_token`) VALUES (?,?,?,?,?,?,?,?,?,?)\nprisma:query ROLLBACK\nprisma:error\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n 16 },\n 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n 18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for\n[next-auth][error][adapter_error_linkAccount]\nhttps://next-auth.js.org/errors#adapter_error_linkaccount\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n 16 },\n 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n 18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for {\n message: '\\n' +\n 'Invalid `p.account.create()` invocation in\\n' +\n '~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\\n' +\n '\\n' +\n ' 16 },\\n' +\n ' 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\\n' +\n ' 18 deleteUser: (id) => p.user.delete({ where: { id } }),\\n' +\n '→ 19 linkAccount: (data) => p.account.create(\\n' +\n \"The provided value for the column is too long for the column's type. Column: for\",\n stack: 'Error: \\n' +\n 'Invalid `p.account.create()` invocation in\\n' +\n '~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\\n' +\n '\\n' +\n ' 16 },\\n' +\n ' 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\\n' +\n ' 18 deleteUser: (id) => p.user.delete({ where: { id } }),\\n' +\n '→ 19 linkAccount: (data) => p.account.create(\\n' +\n \"The provided value for the column is too long for the column's type. Column: for\\n\" +\n ' at fn.handleRequestError (~/node_modules/@prisma/client/runtime/library.js:174:6477)\\n' +\n ' at fn.handleAndLogRequestError (~/node_modules/@prisma/client/runtime/library.js:174:5907)\\n' +\n ' at fn.request (~/node_modules/@prisma/client/runtime/library.js:174:5786)\\n' +\n ' at async t._request (~/node_modules/@prisma/client/runtime/library.js:177:10477)',\n name: 'Error'\n}\n[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]\nhttps://next-auth.js.org/errors#oauth_callback_handler_error\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n 16 },\n 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n 18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for Error:\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n 16 },\n 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n 18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for\n at fn.handleRequestError (~/node_modules/@prisma/client/runtime/library.js:174:6477)\n at fn.handleAndLogRequestError (~/node_modules/@prisma/client/runtime/library.js:174:5907)\n at fn.request (~/node_modules/@prisma/client/runtime/library.js:174:5786)\n at async t._request (~/node_modules/@prisma/client/runtime/library.js:177:10477) {\n name: 'LinkAccountError',\n code: 'P2000'\n}\n```\n\n========================================\n\nCode:\n```text\nprisma:query BEGIN\nprisma:query INSERT INTO `foo`.`Account` (`id`,`userId`,`type`,`provider`,`providerAccountId`,`access_token`,`expires_at`,`token_type`,`scope`,`id_token`) VALUES (?,?,?,?,?,?,?,?,?,?)\nprisma:query ROLLBACK\nprisma:error\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n  16 },\n  17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n  18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for\n[next-auth][error][adapter_error_linkAccount]\nhttps://next-auth.js.org/errors#adapter_error_linkaccount\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n  16 },\n  17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n  18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for {\n  message: '\\n' +\n    'Invalid `p.account.create()` invocation in\\n' +\n    '~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\\n' +\n    '\\n' +\n    '  16 },\\n' +\n    '  17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\\n' +\n    '  18 deleteUser: (id) => p.user.delete({ where: { id } }),\\n' +\n    '→ 19 linkAccount: (data) => p.account.create(\\n' +\n    \"The provided value for the column is too long for the column's type. Column: for\",\n  stack: 'Error: \\n' +\n    'Invalid `p.account.create()` invocation in\\n' +\n    '~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\\n' +\n    '\\n' +\n    '  16 },\\n' +\n    '  17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\\n' +\n    '  18 deleteUser: (id) => p.user.delete({ where: { id } }),\\n' +\n    '→ 19 linkAccount: (data) => p.account.create(\\n' +\n    \"The provided value for the column is too long for the column's type. Column: for\\n\" +\n    '    at fn.handleRequestError (~/node_modules/@prisma/client/runtime/library.js:174:6477)\\n' +\n    '    at fn.handleAndLogRequestError (~/node_modules/@prisma/client/runtime/library.js:174:5907)\\n' +\n    '    at fn.request (~/node_modules/@prisma/client/runtime/library.js:174:5786)\\n' +\n    '    at async t._request (~/node_modules/@prisma/client/runtime/library.js:177:10477)',\n  name: 'Error'\n}\n[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]\nhttps://next-auth.js.org/errors#oauth_callback_handler_error\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n  16 },\n  17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n  18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for Error:\nInvalid `p.account.create()` invocation in\n~/node_modules/@next-auth/prisma-adapter/dist/index.js:19:42\n\n  16 },\n  17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),\n  18 deleteUser: (id) => p.user.delete({ where: { id } }),\n→ 19 linkAccount: (data) => p.account.create(\nThe provided value for the column is too long for the column's type. Column: for\n    at fn.handleRequestError (~/node_modules/@prisma/client/runtime/library.js:174:6477)\n    at fn.handleAndLogRequestError (~/node_modules/@prisma/client/runtime/library.js:174:5907)\n    at fn.request (~/node_modules/@prisma/client/runtime/library.js:174:5786)\n    at async t._request (~/node_modules/@prisma/client/runtime/library.js:177:10477) {\n  name: 'LinkAccountError',\n  code: 'P2000'\n}\n```\n\n```text\nmodel Account {\n  id                String  @id @default(cuid())\n  userId            String\n  type              String\n  provider          String\n  providerAccountId String\n  refresh_token     String? @db.Text\n  access_token      String? @db.Text\n  expires_at        Int?\n  token_type        String?\n  scope             String?\n  id_token          String? @db.Text\n  session_state     String?\n  user              User    @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n  @@unique([provider, providerAccountId])\n  @@index([userId])\n}\n```\n\n```text\n@db.Text\n```\n\n========================================\n\nComments:\n- Related Issue: github.com/nextauthjs/next-auth/issues/4734\n- Thank you so much! They need better error messages. I had the same issue and @db.MediumText fixed it. The logs were telling me the wrong column name, a column name that didn't exist, so I've been so confused for like 2 days.","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":190,"estimatedTokens":2228}}206{"id":"stack-66281332","source":"stackoverflow","questionId":66281332,"title":"Error validating: This line is not a valid field or attribute definition","tags":["prisma"],"text":"Title: Error validating: This line is not a valid field or attribute definition\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI wonder why my **model** (the `Like`-model) does not work as I expect it to.\n\nMaybe someone can explain?\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n likes Like[]\n}\n\nmodel Like {\n fromUser User @relation(fields: [fromUserId] references: [id])\n fromUserId Int\n toUser User @relation(fields: [toUserId] references: [id])\n toUserId Int\n @@id([fromUserId, toUserId])\n}\n```\n\nThe error reads: `Error validating: This line is not a valid field or attribute definition.`\n\nIt points at `fromUser User @relation(fields: [fromUserId] references: [id])` and `toUser User @relation(fields: [toUserId] references: [id])`.\n\n========================================\n\nTop Answer:\nMissing commas.\nThe solution might look like this:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n likes Like[]\n}\n\nmodel Like {\n fromUser User @relation(fields: [fromUserId], references: [id])\n fromUserId Int\n toUser User @relation(fields: [toUserId], references: [id])\n toUserId Int\n @@id([fromUserId, toUserId])\n}\n```\n\n========================================\n\nCode:\n```text\nmodel User {\n  id Int @id @default(autoincrement())\n  likes Like[]\n}\n\nmodel Like {\n  fromUser User @relation(fields: [fromUserId] references: [id])\n  fromUserId Int\n  toUser User @relation(fields: [toUserId] references: [id])\n  toUserId Int\n  @@id([fromUserId, toUserId])\n}\n```\n\n```text\nLike\n```\n\n```text\nError validating: This line is not a valid field or attribute definition.\n```\n\n```text\nfromUser User @relation(fields: [fromUserId] references: [id])\n```\n\n```text\ntoUser User @relation(fields: [toUserId] references: [id])\n```\n\n```text\nmodel User {\n  id            Int    @id @default(autoincrement())\n  likedUsers    Like[] @relation(\"likedUsers\")\n  usersWhoLiked Like[] @relation(\"usersWhoLiked\")\n}\n\nmodel Like {\n  id             Int   @id @default(autoincrement())\n  likedUser      User? @relation(\"likedUsers\", fields: [likedUserId], references: [id])\n  likedUserId    Int?\n  userWhoLiked   User? @relation(\"usersWhoLiked\", fields: [userWhoLikedId], references: [id])\n  userWhoLikedId Int?\n}\n```\n\n```text\nmodel User {\n  id Int @id @default(autoincrement())\n  likes Like[]\n}\n\nmodel Like {\n  fromUser User @relation(fields: [fromUserId], references: [id])\n  fromUserId Int\n  toUser User @relation(fields: [toUserId], references: [id])\n  toUserId Int\n  @@id([fromUserId, toUserId])\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":113,"estimatedTokens":621}}207{"id":"stack-65264609","source":"stackoverflow","questionId":65264609,"title":"Is it possible to access metadata about the prisma model?","tags":["prisma","prisma2"],"text":"Title: Is it possible to access metadata about the prisma model?\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a model in my `schema.prisma` file:\n\n```\nmodel Post {\n id Int @id @default(autoincrement())\n author User @relation(fields: [authorId], references: [id])\n authorId Int\n}\n```\n\nHaving a variable called `model` in my server containing a model name\n\n```\nconst model: string = [model name generated dynamically]\n```\n\nUsing this string I want to know every information about this model. For example if this variable `model` happens to be `Post`, I want to know that it has fields `id, author, authorId` and also information about each field separately, like in the case of `author` which field in which model does it reference, in this example the model `User` the field `id`.\n\nI'm aware that prisma generates a `type` for each `model` and that way maybe I can access the fields that way but that't not enough for me, I want information about each fields as well.\n\nI search the prisma docs, also googled something like 'get meta information about model in prisma2' but I didn't find any solution. Is there a way to achieve this?\n\n========================================\n\nTop Answer:\nBy Prisma version 5.14.0, `prismaClient._dmmf` does not exist. (I don't know in what version it was removed.) However, `prismaClient._runtimeDataModel` now contains model metadata:\n\n```\nconst prismaClient = new PrismaClient();\n\nconst modelData = prismaClient._runtimeDataModel;\n```\n\nIts type is `RuntimeDataModel` from `@prisma/client/runtime/library`. However, `RuntimeDataModel` is not exported by Prisma, so you can obtain the type like this:\n\n```\nimport {defineDmmfProperty} from '@prisma/client/runtime/library';\n\ntype RuntimeDataModel = Parameters[1];\n```\n\n========================================\n\nCode:\n```text\nmodel Post {\n  id        Int   @id @default(autoincrement())\n  author    User  @relation(fields: [authorId], references: [id])\n  authorId  Int\n}\n```\n\n```text\nconst model: string = [model name generated dynamically]\n```\n\n```text\nschema.prisma\n```\n\n```text\nmodel\n```\n\n```text\nmodel\n```\n\n```text\nPost\n```\n\n```text\nid, author, authorId\n```\n\n```text\nauthor\n```\n\n```text\nUser\n```\n\n```text\nid\n```\n\n```text\ntype\n```\n\n```text\nmodel\n```\n\n```text\nconst prisma = new PrismaClient()\n\n// @ts-ignore\nconsole.log(prisma._dmmf)\n```\n\n```js\nconst prismaClient = new PrismaClient();\n\nconst modelData = prismaClient._runtimeDataModel;\n```\n\n```js\nimport {defineDmmfProperty} from '@prisma/client/runtime/library';\n\ntype RuntimeDataModel = Parameters<typeof defineDmmfProperty>[1];\n```\n\n```text\nprismaClient._dmmf\n```\n\n```text\nprismaClient._runtimeDataModel\n```\n\n```text\nRuntimeDataModel\n```\n\n```text\n@prisma/client/runtime/library\n```\n\n```text\nRuntimeDataModel\n```\n\n========================================\n\nComments:\n- Does not work for me.. shows undefined.","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":144,"estimatedTokens":718}}208{"id":"stack-53237538","source":"stackoverflow","questionId":53237538,"title":"Overide entire relation field with Prisma?","tags":["prisma"],"text":"Title: Overide entire relation field with Prisma?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nWith Prisma is it possible to completely overwrite a relation rather than connecting and disconnecting individual nodes? \n\nSay I have a user with a groups relation to groups 1 and 2: \n\n```\nuser: {\n id: \"abcd\"\n groups: [\n {id: 1},\n {id: 2}\n ]\n}\n```\n\nIf I want to make this user only connected to group 3:\n\n```\nuser: {\n id: \"abcd\"\n groups: [\n {id: 3}\n ]\n}\n```\n\nDo I have to do this?: \n\n```\nmutation {\n updateUser(\n where: { id: \"abcd\" }\n data: {\n groups: {\n disconnect: {\n id: \"1\"\n id: \"2\"\n }\n connect: {\n id: \"3\"\n }\n }\n }\n ) {\n id\n }\n}\n```\n\nOr is there some way of overwriting the entire relation:\n\n```\nmutation {\n updateUser(\n where: { id: \"abcd\" }\n data: {\n groups: [{id:3}]\n }\n ) {\n id\n name\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou can use set replace connect\n\n```\ndata: {\n groups: {\n set: {\n id: \"3\"\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nuser: {\n    id: \"abcd\"\n    groups: [\n        {id: 1},\n        {id: 2}\n    ]\n}\n```\n\n```text\nuser: {\n    id: \"abcd\"\n    groups: [\n        {id: 3}\n    ]\n}\n```\n\n```text\nmutation {\n  updateUser(\n    where: { id: \"abcd\" }\n    data: {\n        groups: {\n            disconnect: {\n                id: \"1\"\n                id: \"2\"\n            }\n            connect: {\n                id: \"3\"\n            }\n        }\n    }\n  ) {\n    id\n  }\n}\n```\n\n```text\nmutation {\n  updateUser(\n    where: { id: \"abcd\" }\n    data: {\n        groups: [{id:3}]\n    }\n  ) {\n    id\n    name\n  }\n}\n```\n\n```text\nmutation {\n  createUser(data: {\n    scores: { set: [1, 2, 3] }\n    friends: { set: [\"Sarah\", \"Jane\"] }\n    throws: { set: [false, false] }\n  }) {\n    id\n  }\n}\n```\n\n```text\ndata: {\n    groups: {\n        set: {\n            id: \"3\"\n        }\n    }\n}\n```\n\n========================================\n\nComments:\n- Did you solve this issue? I'm facing the same issue","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":167,"estimatedTokens":483}}209{"id":"stack-73905852","source":"stackoverflow","questionId":73905852,"title":"How to use upsert with Prisma?","tags":["database","prisma"],"text":"Title: How to use upsert with Prisma?\nTags: database, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to either update or create a record in my `Profile` table. I'm using Prisma to define the schema and it looks like this:\n\n```\nmodel Profile {\n id String @id @default(cuid())\n username String?\n about String?\n url String?\n company String?\n userId String\n user User @relation(fields: [userId], references: [id])\n}\n```\n\nI'm calling the upsert function like this:\n\n```\nconst createOrUpdateProfile = await prisma.profile.upsert({\n where: { id: id },\n update: {\n username: username,\n about: about,\n url: url,\n company: company,\n },\n create: {\n username: username,\n about: about,\n url: url,\n company: company,\n user: { connect: { id: userId } },\n },\n });\n```\n\nI'm getting `userId` from session:\n\n```\nconst userId = session.user.id;\n```\n\nI'm getting `id`, `username`, `about`, `url`, and `company` from:\n\n```\n//Passed on from await fetch in the form\nconst { id, username, about, url, company } = req.body;\n```\n\nThe issue I'm having is, whenever I'm trying to provide the `id`, as in `where: { id: id },` and it is not already in the database, it doesn't create a new record.\n\nIf the `id` is not in the database, and I do a `console.log(id)`, it gets back as `undefined`.\n\nIf I manually add a record in `Profile` and connect the user, it updates the record when calling the `upsert` function.\n\nCan you help me spot what I'm doing wrong?\n\n========================================\n\nCode:\n```js\nmodel Profile {\n  id       String  @id @default(cuid())\n  username String?\n  about    String?\n  url      String?\n  company  String?\n  userId   String\n  user     User    @relation(fields: [userId], references: [id])\n}\n```\n\n```js\nconst createOrUpdateProfile = await prisma.profile.upsert({\n      where: { id: id },\n      update: {\n        username: username,\n        about: about,\n        url: url,\n        company: company,\n      },\n      create: {\n        username: username,\n        about: about,\n        url: url,\n        company: company,\n        user: { connect: { id: userId } },\n      },\n    });\n```\n\n```js\nconst userId = session.user.id;\n```\n\n```js\n//Passed on from await fetch in the form\nconst { id, username, about, url, company } = req.body;\n```\n\n```text\nProfile\n```\n\n```text\nuserId\n```\n\n```text\nid\n```\n\n```text\nusername\n```\n\n```text\nabout\n```\n\n```text\nurl\n```\n\n```text\ncompany\n```\n\n```text\nid\n```\n\n```text\nwhere: { id: id },\n```\n\n```text\nid\n```\n\n```text\nconsole.log(id)\n```\n\n```text\nundefined\n```\n\n```text\nProfile\n```\n\n```text\nupsert\n```\n\n```js\nawait prisma.profile.upsert({\n  where: { id: id || '' },\n  // ...\n});\n```\n\n```js\nif (id) {\n  await prisma.profile.update({\n    where: { id },\n    data: {\n      username,\n      about,\n      // ...\n    },\n  });\n} else {\n  await prisma.profile.create({\n    data: {\n      username,\n      about,\n      // ...\n    },\n  });\n}\n```\n\n```text\nid\n```\n\n```text\nundefined\n```\n\n```text\nid\n```\n\n```text\nupsert\n```\n\n```text\nundefined\n```\n\n```text\nid\n```\n\n```text\nundefined\n```\n\n```text\nupsert\n```\n\n```text\nid\n```\n\n```text\nupdate\n```\n\n```text\nupsert\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Can you specify which record is not found? It does not find the `profile` with `id`? But it finds the `user` with `userId`? Do you get an error?\n- @some-user I have updated the original description. I'm getting the `id` from `const { id, username, about, url, company } = req.body; which is from my my fetch function\n- The `userId` is coming from the session, and `id` is coming from reg.body\n- I would like to update a record, if the `id` is found in the database, and if not then it should create a new record as well as connecting it to a user with the `userId`\n- I thought that was the whole purpose of using `upsert`?\n- To my understanding - correct me - your `id` is `undefined`. So you can't look it up in the database but insert it right away.\n- That’s correct. It seems even with your code snippet I’m only able to update a record (given that it is in the database, I.e I manually added it). So I’m back to same behaviour as when I used `upsert` with `where`, `update` and `create` inside it. (See description). So, if I’m getting an empty array back when I’m trying to get the record from the `profile` table, and I’m trying to pass `id` which isn’t there, could that be the issue?\n- Do you get an error message? Or does the `upsert` silently fail? Can you provide a minimal reproducible example?\n- Sorry for the long wait. I figured out if I added `id || \"\"`withing the call instead of in the API route, that it worked that way. I still don't know why it didn't work with the API route though.\n- Somehow, under the hood Prisma compares the format of the provided `id` in the `where` condition of `upsert` to the format required for the db column. So, if you're using UUIDs for record IDs and you pass an empty string as a fallback when `id` is, say, `null`, then you'll get an error when attempting to create the record (second part of `upsert`). For UUIDs, a fallback `id` value of `00000000-0000-0000-0000-000000000000` would work.\n- It worked for me, in my case id is an integer, the fallback id for it to create is 0.\n- This works for UUIDs: await prisma.profile.upsert({ where: { id: id ?? '00000000-0000-0000-0000-000000000000' }, // ... });","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":251,"estimatedTokens":1329}}210{"id":"stack-74020035","source":"stackoverflow","questionId":74020035,"title":"Insert multiple rows with multiple fields with prisma raw query","tags":["prisma"],"text":"Title: Insert multiple rows with multiple fields with prisma raw query\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI couldn't find any examples showing how to do this with integers and my options didn't work out(\n\nMy table contains 2 columns with integers and I need to add multiple rows to it using prisma raw queries.\n\nIf I add just 1 row and use an array of numbers with Prisma.join() - it works fine:\n\n```\nconst testArr = [1,3]\nreturn await this.prisma.$executeRaw`\n INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n VALUES (${Prisma.join(testArr)})\n ON CONFLICT DO NOTHING\n;`\n```\n\nBut when using a template string to add multiple rows at once I'm getting the syntax error:\n\n```\n// Exception:\nINSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n VALUES $1\n ON CONFLICT DO NOTHING\n ; [\"(1,2),(2,2)\"]\nDuration: 0ms\n[Nest] 1226 - 10/08/2022, 11:41:45 AM ERROR [ExceptionsHandler] \nInvalid `prisma.$executeRaw()` invocation:\n \nRaw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near \"$1\"`\n```\n\nI was trying this:\n\n```\nconst testArr = ['(1,2)', '(2,2)']\nreturn await this.prisma.$executeRaw`\n INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n VALUES (${Prisma.join(testArr)})\n ON CONFLICT DO NOTHING\n;`\n```\n\nand this:\n\n```\nconst testArr = ['(1,2)', '(2,2)']\nawait this.prisma.$executeRaw`\n INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n VALUES ${testArr.join(',')}\n ON CONFLICT DO NOTHING\n;`\n```\n\nIt looks like prisma is adding string parentheses around inserted values (but I'm not sure as logs are not very descriptive but it looks like the issue).\n\nPlease advise the workaround.\n\n**Note**: I'm using raw query because of working with unsupported type in other related queries so I need the help with the raw query.\n\n========================================\n\nCode:\n```js\nconst testArr = [1,3]\nreturn await this.prisma.$executeRaw`\n    INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n    VALUES (${Prisma.join(testArr)})\n    ON CONFLICT DO NOTHING\n;`\n```\n\n```js\n// Exception:\nINSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n    VALUES $1\n    ON CONFLICT DO NOTHING\n  ; [\"(1,2),(2,2)\"]\nDuration: 0ms\n[Nest] 1226  - 10/08/2022, 11:41:45 AM   ERROR [ExceptionsHandler] \nInvalid `prisma.$executeRaw()` invocation:\n    \nRaw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near \"$1\"`\n```\n\n```js\nconst testArr = ['(1,2)', '(2,2)']\nreturn await this.prisma.$executeRaw`\n    INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n    VALUES (${Prisma.join(testArr)})\n    ON CONFLICT DO NOTHING\n;`\n```\n\n```js\nconst testArr = ['(1,2)', '(2,2)']\nawait this.prisma.$executeRaw`\n    INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\")\n    VALUES ${testArr.join(',')}\n    ON CONFLICT DO NOTHING\n;`\n```\n\n```js\nconst testArr = [\n    [1, 2],\n    [2, 2],\n  ];\n```\n\n```text\nmodel Foo {\n  id String @id @default(dbgenerated(\"gen_random_uuid()\")) @db.Uuid\n  a  Int\n  b  Int\n}\n```\n\n```js\nawait prisma.$executeRaw`\n  INSERT INTO \"Foo\" (\"b\", \"a\")\n  VALUES ${Prisma.join(\n    testArr.map((row) => Prisma.sql`(${Prisma.join(row)})`)\n  )}\n  ON CONFLICT DO NOTHING;`;\n```\n\n```text\n'(1,2)'\n```\n\n```text\nPrisma.join\n```\n\n```text\nPrisma.sql\n```\n\n========================================\n\nComments:\n- Also I've checked that it works with the executeRawUnsafe but I think it's not a good option due to possible SQL injections: `return await this.prisma.$executeRawUnsafe( `INSERT INTO public.\"_CategoryToItem\" (\"B\", \"A\") VALUES ${testArr.join(',')} ON CONFLICT DO NOTHING ;`)`\n- You helped me out so much. I tried to mess with the syntax of making this happen for far too long before I found this answer. Thx!\n- Thanks! This answer helped but I have another problem. I'm using this approach to bulk insert records in 50k batches. The problem is this code exceeds the Postgres max bind variables of 32767 in a prepared statement. I can't find it anywhere but is there are way to compile this SQL into its full statement and execute it directly against the db? This way I can benefit from the Prisma safe query and escaping etc, and still do the bug insert.\n- @mbrookson build the query and use rawUnsafe()/Prisma.raw. Easiest to limit batch sizes.\n- It seems that with SQL Server, the maximum number of parameters is as low as 2100.\n- @leppaott and is on it name unsafe, if anyone sql injection could drop ur DB entirely","metadata":{"transformedAt":"2026-08-18T18:33:14.837Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":151,"estimatedTokens":1082}}211{"id":"stack-70609251","source":"stackoverflow","questionId":70609251,"title":"Prisma - How to use count as a where condition with relation","tags":["prisma","prisma2"],"text":"Title: Prisma - How to use count as a where condition with relation\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI use `nestjs` and `postgresql` with `prisma`. I have 2 tables in relation, I want to create a where clause in order to fetch the records if count of the records in the second table is less than -let's say- 3. More details;\n\nHere is my schema\n\n```\nmodel User {\n id String @id\n someOtherFields String\n outgoingPlayMateRequest PlayMateRequest[] @relation(\"userId\")\n incomingPlayMateRequest PlayMateRequest[] @relation(\"targetId\")\n}\n\nmodel PlayMateRequest {\n id Int @id\n requestingUser User @relation(name: \"userId\", fields: [requestingUserId], references: [id], onDelete: Cascade)\n targetUser User @relation(name: \"targetId\", fields: [targetUserId], references: [id], onDelete: Cascade)\n requestingUserId String\n targetUserId String\n someOtherFields String\n response String //accept-reject-block\n}\n```\n\nand here is my code with where clause (I am simplfying it by removing unrelevant parts)\n\n```\nconst userId = 'testUser';\nreturn await this.prismaService.user.findMany({\n where: {\n NOT: {\n id: userId //don't fetch user him/herself\n },\n lang: 'EN',\n }\n });\n```\n\n**The condition I want to add here** in english is;\n\nDon't select users with incomingPlayMateRequest relation, if there are\n3 records in PlayMateRequest table with `response = reject` AND\n`requestingUser = userId`\n\nBut I couldn't find anyway to use `count` as a condition in where. As I see I can only get the relations count. How can I do this with `prisma`?\n\n========================================\n\nCode:\n```text\nmodel User {\n  id                      String            @id\n  someOtherFields         String\n  outgoingPlayMateRequest PlayMateRequest[] @relation(\"userId\")\n  incomingPlayMateRequest PlayMateRequest[] @relation(\"targetId\")\n}\n\nmodel PlayMateRequest {\n  id               Int      @id\n  requestingUser   User     @relation(name: \"userId\", fields: [requestingUserId], references: [id], onDelete: Cascade)\n  targetUser       User     @relation(name: \"targetId\", fields: [targetUserId], references: [id], onDelete: Cascade)\n  requestingUserId String\n  targetUserId     String\n  someOtherFields  String\n  response         String   //accept-reject-block\n}\n```\n\n```text\nconst userId = 'testUser';\nreturn await this.prismaService.user.findMany({\n    where: {\n      NOT: {\n        id: userId //don't fetch user him/herself\n      },\n      lang: 'EN',\n    }\n  });\n```\n\n```text\nnestjs\n```\n\n```text\npostgresql\n```\n\n```text\nprisma\n```\n\n```text\nresponse = reject\n```\n\n```text\nrequestingUser = userId\n```\n\n```text\ncount\n```\n\n```text\nprisma\n```\n\n```js\nconst userId = 'testUser';\n\n// step 1\nconst dataForFilter = await prisma.playMateRequest.groupBy({\n    by: ['targetUserId'],\n    where: {\n        response: \"reject\",\n        requestingUserId: userId\n    },\n    having: {\n        targetUserId: {\n            _count: {\n                equals: 3  \n            }\n        }\n    }\n})\n\n// step 2\nlet exclude_users = [userId]\nexclude_users = exclude_users.concat(dataForFilter.map(item => item.targetUserId))\n\nlet result = await prisma.playMateRequest.user.findMany({\n    where: {\n        id: {\n        notIn: exclude_users\n        },\n        lang: \"en\"\n    }\n    });\n```\n\n```text\ngroupBy\n```\n\n```text\nmap\n```\n\n```text\nUser.id\n```\n\n```text\nfindMany\n```\n\n```text\nnotIn\n```\n\n```text\ngroupBy\n```\n\n========================================\n\nComments:\n- Hi, sorry for the late response. I was hoping there would be a direct way but this is a solution. Thanks for the help @Tasin Ishmam\n- Welcome, happy to help!","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":174,"estimatedTokens":896}}212{"id":"stack-72981965","source":"stackoverflow","questionId":72981965,"title":"Does Prisma support composite keys with one of the attribute being NULL for PostgreSQL?","tags":["prisma"],"text":"Title: Does Prisma support composite keys with one of the attribute being NULL for PostgreSQL?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nIn PostgreSQL you can make a table with 2 columns as the composite key of that table, with one of them being NULL-able. I was just wondering how I can achieve this with Prisma.\n\nIn the current version of Prisma that I have (3.14.0), Prisma does allow composite key using `@@id([column1,column2])`, but only if those two columns are mandatory.\n\n========================================\n\nCode:\n```text\n@@id([column1,column2])\n```\n\n```text\nmodel Post {\n  title   String\n  content String\n\n  @@id([title, content])\n}\n```\n\n```text\nmodel Post {\n  title   String\n  content String?\n\n  @@id([title, content])\n}\n```\n\n========================================\n\nComments:\n- In fact, there's an old issue regarding this: github.com/prisma/prisma/issues/3197. The OP states that an attempt to create such an index results in a runtime error","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":38,"estimatedTokens":242}}213{"id":"stack-68610423","source":"stackoverflow","questionId":68610423,"title":"Prisma findMany function is not returning relational data","tags":["javascript","postgresql","prisma"],"text":"Title: Prisma findMany function is not returning relational data\nTags: javascript, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to populate my data with relational data using Prisma 2.28.0, Here is my\n\nSchema.prisma model below\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel Product {\n id Int @id @default(autoincrement())\n name String @db.VarChar(255)\n transactions Transaction[]\n}\n\nmodel Transaction {\n id BigInt @id @default(autoincrement())\n quantity Int\n time Int\n product Product? @relation(fields: [productId], references: [id])\n productId Int?\n}\n```\n\nthe function I am trying to fetch data.\n\n```\nconst { PrismaClient }=require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function checkPrismaConnection(){\n try {\n const result=await prisma.product.findMany();\n console.log(result);\n }catch (e) {\n console.log(e);\n }\n}\n\n checkPrismaConnection();\n```\n\nOutPut\n\n```\n[\n { id: 1, name: 'John Doe' },\n { id: 2, name: 'Masum' },\n { id: 3, name: 'Rezaul' }\n]\n```\n\nTransaction DB result\nhttps://i.sstatic.net/GGJpu.png\n\nProduct DB\n\nhttps://i.sstatic.net/B7y8y.png\n\nI don't know why my findMany() is not retuning relational db data. Thank you\n\n========================================\n\nTop Answer:\nYou need to explicitly set include to true.\n\nSo the code will look like this for you\n\n```\nconst { PrismaClient }=require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function checkPrismaConnection(){\n try {\n const result=await prisma.product.findMany({\n include: {\n transaction: true,\n },\n });\n console.log(result);\n}catch (e) {\n console.log(e);\n}\n}\n\n checkPrismaConnection();\n```\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Product {\n  id           Int         @id @default(autoincrement())\n  name         String         @db.VarChar(255)\n  transactions Transaction[]\n}\n\nmodel Transaction {\n  id        BigInt   @id @default(autoincrement())\n  quantity  Int\n  time      Int\n  product  Product? @relation(fields: [productId], references: [id])\n  productId Int?\n}\n```\n\n```text\nconst { PrismaClient }=require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function checkPrismaConnection(){\n    try {\n        const result=await prisma.product.findMany();\n        console.log(result);\n    }catch (e) {\n        console.log(e);\n    }\n}\n\n checkPrismaConnection();\n```\n\n```text\n[\n  { id: 1, name: 'John Doe' },\n  { id: 2, name: 'Masum' },\n  { id: 3, name: 'Rezaul' }\n]\n```\n\n```js\nconst getPosts = await prisma.post.findMany({\n  where: {\n    title: {\n      contains: 'cookies',\n    },\n  },\n  include: {\n    author: true, // Return all fields\n  },\n})\n```\n\n```text\nAuthor\n```\n\n```text\nPost\n```\n\n```text\nPost\n```\n\n```text\nauthor\n```\n\n```text\nAuthor\n```\n\n```text\n.category\n```\n\n```text\n.transactions\n```\n\n```text\nconst { PrismaClient }=require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function checkPrismaConnection(){\n   try {\n    const result=await prisma.product.findMany({\n      include: {\n        transaction: true,\n       },\n   });\n    console.log(result);\n}catch (e) {\n    console.log(e);\n}\n}\n\n checkPrismaConnection();\n```\n\n========================================\n\nComments:\n- The screenshot of your database result seems to be a result of transactions (that reference a product id), while your code seems to be querying just products. Copied the code/screenshot incorrectly or so?\n- I've attached product db screenshot now and updated my question.\n- If I use it It pupulates relation db as an object, but other record who doesn't have any relation with others is not showing..\n- Not sure what exactly what you're problem is. Perhaps close this question and create a new one with your updated code and its updated (and expected) results.","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":222,"estimatedTokens":987}}214{"id":"stack-72237109","source":"stackoverflow","questionId":72237109,"title":"Prisma SQLite List","tags":["sqlite","prisma"],"text":"Title: Prisma SQLite List\nTags: sqlite, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a List to a model using `String[]` but it it gives me this error:\n\n```\nField \"stats\" in model \"Player\" can't be a list.\nThe current connector does not support lists of primitive types.\n```\n\nCode:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"sqlite\"\n url = \"file:./db.db\"\n}\n\nmodel Player {\n id String @id @default(cuid())\n stats String[]\n}\n```\n\nIs there a way to do this?\n\n========================================\n\nCode:\n```text\nField \"stats\" in model \"Player\" can't be a list.\nThe current connector does not support lists of primitive types.\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"sqlite\"\n  url      = \"file:./db.db\"\n}\n\nmodel Player {\n  id String @id @default(cuid())\n  stats String[]\n}\n```\n\n```text\nString[]\n```\n\n```text\nunset\n```\n\n```text\npush\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":67,"estimatedTokens":237}}215{"id":"stack-52710372","source":"stackoverflow","questionId":52710372,"title":"Include relationship when querying node using Prisma generated wrapper","tags":["graphql","prisma","plumatic-schema","prisma-graphql"],"text":"Title: Include relationship when querying node using Prisma generated wrapper\nTags: graphql, prisma, plumatic-schema, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am following the GraphQL Prisma Typescript example provided by Prisma and created a simple data model, generated the code for the Prisma client and resolvers, etc.\n\nMy data model includes the following nodes:\n\n```\ntype User {\n id: ID! @unique\n displayName: String!\n}\n\ntype SystemUserLogin {\n id: ID! @unique\n username: String! @unique\n passwordEnvironmentVariable: String!\n user: User!\n}\n```\n\nI've seeded with a system user and user.\n\n```\nmutation {\n systemUserLogin: createSystemUserLogin({\n data: {\n username: \"SYSTEM\",\n passwordEnvironmentVariable: \"SYSTEM_PASSWORD\",\n user: {\n create: {\n displayName: \"System User\"\n }\n }\n }\n })\n}\n```\n\nI've created a sample mutation `login`:\n\n```\nlogin: async (_parent, { username, password }, ctx) => {\n let user\n const systemUser = await ctx.db.systemUserLogin({ username })\n const valid = systemUser && systemUser.passwordEnvironmentVariable && process.env[systemUser.passwordEnvironmentVariable] &&(process.env[systemUser.passwordEnvironmentVariable] === password)\n\n if (valid) {\n user = systemUser.user // this is always undefined!\n }\n\n if (!valid || !user) {\n throw new Error('Invalid Credentials')\n }\n\n const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)\n\n return {\n token,\n user: ctx.db.user({ id: user.id }),\n }\n },\n```\n\nBut no matter what I do, `systemUser.user` is ALWAYS undefined!\n\nThis makes sense - how would the client wrapper know how \"deep\" to recurse into the graph without me telling it?\n\nBut how can I tell it that I want to include the `User` relationship?\n\n### Edit: I tried the suggestion below to use `prisma-client`.\n\nBut none of my resolvers ever seem to get called...\n\n```\nexport const SystemUserLogin: SystemUserLoginResolvers.Type = {\n id: parent => parent.id,\n user: (parent, args, ctx: any) => {\n console.log('resolving')\n return ctx.db.systemUserLogin({id: parent.id}).user()\n },\n environmentVariable: parent => parent.environmentVariable,\n systemUsername: parent => parent.systemUsername,\n createdAt: parent => parent.createdAt,\n updatedAt: parent => parent.updatedAt\n};\n```\n\nAnd...\n\n```\nlet identity: UserParent;\n\n const systemUserLogins = await context.db.systemUserLogins({\n where: {\n systemUsername: user,\n }\n });\n const systemUserLogin = (systemUserLogins) ? systemUserLogins[0] : null ;\n\n if (systemUserLogin && systemUserLogin.environmentVariable && process.env[systemUserLogin.environmentVariable] && process.env[systemUserLogin.environmentVariable] === password) {\n console.log('should login!')\n\n identity = systemUserLogin.user; // still null\n }\n```\n\n### Edit 2: Here is the repository\n\nhttps://github.com/jshin47/annotorious/tree/master/server\n\n========================================\n\nTop Answer:\nSecond parameter of prisma binding functions accept GraphQL query string. Changing following line from\n\n```\nconst systemUser = await ctx.db.query.systemUserLogin({ username })\n```\n\nto\n\n```\nconst systemUser = await ctx.db.query.systemUserLogin({ username }, `{id username user {id displayName}}`)\n```\n\nwill give you the data of user.\n\nPrisma binding will return only direct properties of model in case second parameter is not passed to it.\n\n========================================\n\nCode:\n```text\ntype User {\n  id: ID! @unique\n  displayName: String!\n}\n\ntype SystemUserLogin {\n  id: ID! @unique\n  username: String! @unique\n  passwordEnvironmentVariable: String!\n  user: User!\n}\n```\n\n```text\nmutation {\n  systemUserLogin: createSystemUserLogin({\n    data: {\n      username: \"SYSTEM\",\n      passwordEnvironmentVariable: \"SYSTEM_PASSWORD\",\n      user: {\n        create: {\n          displayName: \"System User\"\n        }\n      }\n    }\n  })\n}\n```\n\n```text\nlogin: async (_parent, { username, password }, ctx) => {\n    let user\n    const systemUser = await ctx.db.systemUserLogin({ username })\n    const valid = systemUser && systemUser.passwordEnvironmentVariable && process.env[systemUser.passwordEnvironmentVariable] &&(process.env[systemUser.passwordEnvironmentVariable] === password)\n\n    if (valid) {\n      user = systemUser.user // this is always undefined!\n    }\n\n    if (!valid || !user) {\n      throw new Error('Invalid Credentials')\n    }\n\n    const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)\n\n    return {\n      token,\n      user: ctx.db.user({ id: user.id }),\n    }\n  },\n```\n\n```text\nexport const SystemUserLogin: SystemUserLoginResolvers.Type<TypeMap> = {\n  id: parent => parent.id,\n  user: (parent, args, ctx: any) => {\n    console.log('resolving')\n    return ctx.db.systemUserLogin({id: parent.id}).user()\n  },\n  environmentVariable: parent => parent.environmentVariable,\n  systemUsername: parent => parent.systemUsername,\n  createdAt: parent => parent.createdAt,\n  updatedAt: parent => parent.updatedAt\n};\n```\n\n```text\nlet identity: UserParent;\n\n  const systemUserLogins = await context.db.systemUserLogins({\n    where: {\n      systemUsername: user,\n    }\n  });\n  const systemUserLogin = (systemUserLogins) ? systemUserLogins[0] : null ;\n\n  if (systemUserLogin && systemUserLogin.environmentVariable && process.env[systemUserLogin.environmentVariable] && process.env[systemUserLogin.environmentVariable] === password) {\n    console.log('should login!')\n\n    identity = systemUserLogin.user; // still null\n  }\n```\n\n```text\nlogin\n```\n\n```text\nsystemUser.user\n```\n\n```text\nUser\n```\n\n```text\nprisma-client\n```\n\n```text\ntype SystemUserLogin {\n  id: ID! @unique\n  username: String! @unique\n  passwordEnvironmentVariable: String!\n  user: User! # GraphQL doesn't know how to resolve this\n}\n```\n\n```text\nconst resolvers = {\n  SystemUserLogin: {\n    user(parent, args, ctx) {\n      return ctx.db.systemUserLogin({id: parent.id}).user()\n    }\n  } \n}\n```\n\n```text\n$fragment\n```\n\n```text\nuser\n```\n\n```text\nSystemUserLogin\n```\n\n```text\nauthor\n```\n\n```text\nposts\n```\n\n```text\nconst systemUser = await ctx.db.query.systemUserLogin({ username })\n```\n\n```text\nconst systemUser = await ctx.db.query.systemUserLogin({ username }, `{id username user {id displayName}}`)\n```\n\n========================================\n\nComments:\n- I was really hoping this sort of thing would work, but I tried and it doesn't, and the method's interface suggests that it only accepts one parameter anyway: `systemUserLogin: (where: SystemUserLoginWhereUniqueInput) => SystemUserLogin;`\n- And `ctx.db.query` is `undefined`\n- Are you setting `db` in context while initialising your server?\n- Yes, but I was importing the wrong `Prisma`, I guess... `import {Prisma} from \".&#47;generated&#47;prisma\";` works, `import {Prisma} from \".&#47;generated&#47;prisma-client\";` doesnt\n- There are two ways to query data from Prisma. You can either use `prisma-binding` or `prisma-client`. My answer uses `prisma-binding`. For `prisma-client`, this is how relationships are queried: prisma.io/docs/prisma-client/basic-data-access/&hellip;\n- Sorry for the confusion around Prisma client and Prisma bindings. Hope my answer helps 🙌\n- Thank you for the detailed answer. I was wondering what the difference was! I have found the documentation to be wanting, so this really helps.\n- I tried your suggestion using `prisma-client` and it seems like my resolver is never actually called, so I am still unable to get it to work with `prisma-client`\n- Hmm this is strange! Did you double check that the resolvers are actually passed to your GraphQL server? Normally when a query is resolved, the resolvers for *all* fields inside the query should be called! So if you're sending a query that uses the `user` of `SystemUserLogin` the `user` resolver should get called. If no, there might be an issue somewhere else!\n- Were you able to resolve the issue in the meantime @tacos_tacos_tacos? Is the resolver still not called?\n- The resolver is still not called... tonight when I get home I will copy and paste the code from the entry point on down... Any ideas?\n- Do you maybe have a link to a GitHub repo so I can reproduce the issue? Currently it's difficult for me to tell where the error is since my understanding is that the resolver *should* be called. So I believe the point we need to investigate is why it is not called.\n- any idea about what's going wrong with my example? I provided a link to repo","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":298,"estimatedTokens":2084}}216{"id":"stack-69323946","source":"stackoverflow","questionId":69323946,"title":"Electron-Prisma Error: can not find module '.prisma/client'","tags":["javascript","node.js","electron","nuxt.js","prisma"],"text":"Title: Electron-Prisma Error: can not find module '.prisma/client'\nTags: javascript, node.js, electron, nuxt.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :\n\n```\nA javascript error occurred in the main process\nUncaught exception:\nError: can not find module : '.prisma/client'\n```\n\nI tried changing prisma provider output to `../resources/prisma/client`\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../resources/prisma/client\"\n}\n```\n\nand in main.js of electron\n\n```\nconst { PrismaClient } = require('../resources/prisma/client');\nconst prisma = new PrismaClient()\n```\n\nbut I get error `Cannot find module '_http_common' at webpackMissingModules` in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on `background.js` (`main.js` of the my boilerplate)\n\nI'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:\n\n```\nappId: com.example.app\nproductName: nuxt-electron-prisma\ncopyright: Copyright © 2021\nnsis: \n oneClick: false\n perMachine: true\n allowToChangeInstallationDirectory: true\n\ndirectories:\n output: dist\n buildResources: resources\nfiles:\n - \"resources/prisma/database.db\"\n - \"node_modules/.prisma/**\"\n - \"node_modules/@prisma/client/**\"\n - from: .\n filter:\n - package.json\n - app\npublish: null\n```\n\nand still get errors\n\nin my `win-unpacked/resources` I have this only: `win-unpacked\\resources\\app.asar.unpacked\\node_modules\\@prisma\\engines`\n\nhttps://i.sstatic.net/wMyij.png\n\nand of course my package.json\n\n```\n{\n \"private\": true,\n \"name\": \"nuxt-electron-prisma\",\n \"productName\": \"nuxt-electron-prisma\",\n \"description\": \"\",\n \"version\": \"1.0.0\",\n \"author\": \"\",\n \"main\": \"app/background.js\",\n \"scripts\": {\n \"dev\": \"nuxtron\",\n \"build\": \"nuxtron build\"\n },\n \"dependencies\": {\n \"electron-serve\": \"^1.0.0\",\n \"electron-store\": \"^6.0.1\",\n \"@prisma/client\": \"^3.0.2\"\n },\n \"devDependencies\": {\n \"@mdi/font\": \"^6.1.95\",\n \"@nuxtjs/axios\": \"^5.13.6\",\n \"@nuxtjs/device\": \"^2.1.0\",\n \"@nuxtjs/dotenv\": \"^1.4.1\",\n \"@nuxtjs/vuetify\": \"1.12.1\",\n \"core-js\": \"^3.15.1\",\n \"electron\": \"^10.1.5\",\n \"electron-builder\": \"^22.9.1\",\n \"glob\": \"^7.1.7\",\n \"noty\": \"^3.2.0-beta\",\n \"nuxt\": \"^2.15.7\",\n \"nuxtron\": \"^0.3.1\",\n \"sass\": \"1.32.13\",\n \"swiper\": \"^5.4.5\",\n \"prisma\": \"^3.0.2\",\n \"vue-awesome-swiper\": \"^4.1.1\"\n }\n}\n```\n\n========================================\n\nTop Answer:\nOk, I finally solved it!!\nfirst of all no need to change client generator output direction!\n\n```\n//schema.prisma\ndatasource db {\n provider = \"sqlite\"\n url = \"file:../resources/database.db\"\n}\ngenerator client {\n provider = \"prisma-client-js\"\n // output = \"../resources/prisma/client\" !! no need for this!\n}\n```\n\nthen in electron-builder config add `./prisma` , `@prisma` and database\n\n```\n// my config file was a .yml\nextraResources:\n - \"resources/database.db\"\n - \"node_modules/.prisma/**/*\"\n - \"node_modules/@prisma/client/**/*\"\n\n// or in js\nextraResources:[\n \"resources/database.db\"\n \"node_modules/.prisma/**/*\"\n \"node_modules/@prisma/client/**/*\"\n]\n```\n\nthis solved `Error: cannot find module : '.prisma/client'\n\nbut this alone won't read DB in built exe file!\n\nso in main.js where importing `@prisma/client` should change DB reading directory:\n\n```\nimport { join } from 'path';\nconst isProd = process.env.NODE_ENV === 'production';\n\nimport { PrismaClient } from '@prisma/client';\nconst prisma = new PrismaClient({\n datasources: {\n db: {\n url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,\n },\n },\n})\n```\n\nwith these configs I could fetch data from my sqlite DB\n\n========================================\n\nCode:\n```text\nA javascript error occurred in the main process\nUncaught exception:\nError: can not find module : '.prisma/client'\n```\n\n```js\ngenerator client {\n  provider = \"prisma-client-js\"\n  output   = \"../resources/prisma/client\"\n}\n```\n\n```js\nconst { PrismaClient } = require('../resources/prisma/client');\nconst prisma = new PrismaClient()\n```\n\n```yaml\nappId: com.example.app\nproductName: nuxt-electron-prisma\ncopyright: Copyright © 2021\nnsis: \n  oneClick: false\n  perMachine: true\n  allowToChangeInstallationDirectory: true\n\ndirectories:\n  output: dist\n  buildResources: resources\nfiles:\n  - \"resources/prisma/database.db\"\n  - \"node_modules/.prisma/**\"\n  - \"node_modules/@prisma/client/**\"\n  - from: .\n    filter:\n      - package.json\n      - app\npublish: null\n```\n\n```json\n{\n  \"private\": true,\n  \"name\": \"nuxt-electron-prisma\",\n  \"productName\": \"nuxt-electron-prisma\",\n  \"description\": \"\",\n  \"version\": \"1.0.0\",\n  \"author\": \"\",\n  \"main\": \"app/background.js\",\n  \"scripts\": {\n    \"dev\": \"nuxtron\",\n    \"build\": \"nuxtron build\"\n  },\n  \"dependencies\": {\n    \"electron-serve\": \"^1.0.0\",\n    \"electron-store\": \"^6.0.1\",\n    \"@prisma/client\": \"^3.0.2\"\n  },\n  \"devDependencies\": {\n    \"@mdi/font\": \"^6.1.95\",\n    \"@nuxtjs/axios\": \"^5.13.6\",\n    \"@nuxtjs/device\": \"^2.1.0\",\n    \"@nuxtjs/dotenv\": \"^1.4.1\",\n    \"@nuxtjs/vuetify\": \"1.12.1\",\n    \"core-js\": \"^3.15.1\",\n    \"electron\": \"^10.1.5\",\n    \"electron-builder\": \"^22.9.1\",\n    \"glob\": \"^7.1.7\",\n    \"noty\": \"^3.2.0-beta\",\n    \"nuxt\": \"^2.15.7\",\n    \"nuxtron\": \"^0.3.1\",\n    \"sass\": \"1.32.13\",\n    \"swiper\": \"^5.4.5\",\n    \"prisma\": \"^3.0.2\",\n    \"vue-awesome-swiper\": \"^4.1.1\"\n  }\n}\n```\n\n```text\n../resources/prisma/client\n```\n\n```text\nCannot find module '_http_common' at webpackMissingModules\n```\n\n```text\nbackground.js\n```\n\n```text\nmain.js\n```\n\n```text\nwin-unpacked/resources\n```\n\n```text\nwin-unpacked\\resources\\app.asar.unpacked\\node_modules\\@prisma\\engines\n```\n\n```json\n{\n  \"build\": {\n    \"extraResources\": [\n      {\n        \"from\": \"node_modules/.prisma/client/\",\n        \"to\": \"app/node_modules/.prisma/client/\"\n      }\n    ],\n  }\n}\n```\n\n```json\n{\n  \"build\": {\n    \"files\": [\n      {\n        \"from\": \"node_modules/.prisma/client/\",\n        \"to\": \"node_modules/.prisma/client/\"\n      }\n    ],\n  }\n}\n```\n\n```text\n@prisma\n```\n\n```text\nresources/app/node_modules\n```\n\n```text\nresources/node_modules\n```\n\n```text\nresources/app/node_modules\n```\n\n```text\n@prisma\n```\n\n```text\nfiles\n```\n\n```text\n//schema.prisma\ndatasource db {\n  provider = \"sqlite\"\n  url      = \"file:../resources/database.db\"\n}\ngenerator client {\n  provider = \"prisma-client-js\"\n  // output   = \"../resources/prisma/client\"  !! no need for this!\n}\n```\n\n```js\n// my config file was a .yml\nextraResources:\n  - \"resources/database.db\"\n  - \"node_modules/.prisma/**/*\"\n  - \"node_modules/@prisma/client/**/*\"\n\n// or in js\nextraResources:[\n  \"resources/database.db\"\n  \"node_modules/.prisma/**/*\"\n  \"node_modules/@prisma/client/**/*\"\n]\n```\n\n```js\nimport { join } from 'path';\nconst isProd = process.env.NODE_ENV === 'production';\n\nimport { PrismaClient } from '@prisma/client';\nconst prisma = new PrismaClient({\n  datasources: {\n    db: {\n      url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,\n    },\n  },\n})\n```\n\n```text\n./prisma\n```\n\n```text\n@prisma\n```\n\n```text\n@prisma/client\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":369,"estimatedTokens":1809}}217{"id":"stack-76244244","source":"stackoverflow","questionId":76244244,"title":"Profile id is missing in Google OAuth profile response - NextAuth","tags":["typescript","next.js","prisma","next-auth","t3"],"text":"Title: Profile id is missing in Google OAuth profile response - NextAuth\nTags: typescript, next.js, prisma, next-auth, t3\nSource: Stack Overflow\n\nQuestion:\nI'm following this tutorial on how to add roles in next-auth session.\nUnfortunately, when I add `profile` property, I get undefined behavior of the profile missing. There are also errors regarding typescript. Is this an error on my side, or is it a known bug, since I couldn't find anything on it.\n\nHere's my code so far:\n\n```\nexport const authOptions: AuthOptions = {\n secret: process.env.NEXT_PUBLIC_SECRET!,\n providers: [\n GoogleProvider({\n clientId: process.env.GOOGLE_CLIENT_ID!,\n clientSecret: process.env.GOOGLE_CLIENT_SECRET!,\n // profile: async (profile) => {\n // return { ...profile, role: profile.role ?? Role.USER };\n // },\n }),\n ],\n pages: {\n signIn: \"/\",\n },\n\n adapter: PrismaAdapter(prisma),\n};\n```\n\nas you can see it's the same as the one from the tutorial, when I comment out the profile section I get the expected behavior without role. Any help would be appreciated!\n\nVersion of Next.js: 13.4.1 (app directory)\n\n========================================\n\nCode:\n```text\nexport const authOptions: AuthOptions = {\n  secret: process.env.NEXT_PUBLIC_SECRET!,\n  providers: [\n    GoogleProvider({\n      clientId: process.env.GOOGLE_CLIENT_ID!,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,\n      // profile: async (profile) => {\n      //   return { ...profile, role: profile.role ?? Role.USER };\n      // },\n    }),\n  ],\n  pages: {\n    signIn: \"/\",\n  },\n\n  adapter: PrismaAdapter(prisma),\n};\n```\n\n```text\nprofile\n```\n\n```html\nGoogleProvider({\n            clientId: process.env.GOOGLE_ID,\n            clientSecret: process.env.GOOGLE_SECRET,\n            authorization: {\n                params: {\n                    prompt: \"consent\",\n                    access_type: \"offline\",\n                    response_type: \"code\"\n                }\n            },\n            async profile(profile) {\n\n                return {\n                    id: profile.sub,\n                    name: profile.name,\n                    firstname: profile.given_name,\n                    lastname: profile.family_name,\n                    email: profile.email,\n                    image: profile.picture,\n                }\n            },\n        }),\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":90,"estimatedTokens":660}}218{"id":"stack-76321912","source":"stackoverflow","questionId":76321912,"title":"Error: P3017 When I run npx prisma command","tags":["next.js","prisma"],"text":"Title: Error: P3017 When I run npx prisma command\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nwhen I hit `npx prisma migrate resolve --applied 0_init` in command line. bellow error occurred:\n\n**Error: P3017\n\nThe migration 0_init could not be found. Please make sure that the migration exists, and that you included the whole name of the directory. (example: \"20201207184859_initial_migration\")**\n\nI want to use mysql tables in my own next js project .\n\nAccording to this url, I can do that using prisma orm.\n\nbut Im stock in this step : `npx prisma migrate resolve --applied 0_init`\n\n========================================\n\nTop Answer:\nI just encounted exactly the same issue as yours. My environment: VSCode1.78 on a Windows10 .\nI was struck in my VSCode terminal, which by default is a powershell.\n\nFortunately I got inspiration from comments to the end of this thread:\nhttps://github.com/prisma/prisma/issues/17558\n\nThen I switched to a \"cmd\" terminal in VSCode to execute the same command, and the problem just disappeared.\n\nSo I am sure the problem was caused by some difference between Powshell terminal and \"cmd\" terminal.\n\nBy the way, I tried the \"npx prisma migrate resolve --applied 0_init\" command in a git bash terminal outside of VSCode. All good there too.\n\n========================================\n\nCode:\n```text\nnpx prisma migrate resolve --applied 0_init\n```\n\n```text\nnpx prisma migrate resolve --applied 0_init\n```\n\n```text\nmigration.sql\n```\n\n```text\nwindow1252\n```\n\n```text\nnpx prisma migrate diff > migration.sql\n```\n\n========================================\n\nComments:\n- tnx for replies . I tried in both cmd and git bash in root of project location . but error persist\n- Bravo guy, You are the only one who solved my problem. thank you.\n- According to this answer we need to do these in cmd(run as administrator): 1- npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql 2- npx prisma migrate resolve --applied 0_init\n- Changing to UTF-8 worked for me too.","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":517}}219{"id":"stack-66646432","source":"stackoverflow","questionId":66646432,"title":"How do I run Prisma migrations in a Dockerized GraphQL + Postgres setup?","tags":["postgresql","docker","docker-compose","dockerfile","prisma"],"text":"Title: How do I run Prisma migrations in a Dockerized GraphQL + Postgres setup?\nTags: postgresql, docker, docker-compose, dockerfile, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm new to using Prisma as well as Dockerizing my setup. I would like to specify my data model using Prisma, have Postgres as my database and use that in a GraphQL API (my current API uses `apollo-server-express`) that also deals with authentication and roles etc.\n\nWhat I have now is a simple `docker-compose.yml` and a `Dockerfile` of my GraphQL API:\n\n### docker-compose.yml\n\n```\nservices:\n api:\n build: ./api\n env_file:\n - .env\n volumes:\n - ./api:/usr/src/app\n ports:\n - ${API_PORT}:${API_PORT}\n command: npm start\n```\n\n### Dockerfile\n\n```\n# Latest LTS version\nFROM node:14\n\n# Set default values for environment variables\nENV API_PORT=3001\n\n# Create app directory\nWORKDIR /usr/src/app\n\n# Install app dependencies\nCOPY package*.json ./\nRUN npm install\n\n# Bundle app source\nCOPY . .\n\n# Bind port\nEXPOSE ${API_PORT}\n\n# Start server\nCMD [\"npm\", \"start\"]\n```\n\nHow would I go about using Prisma and Postgres in this setup, where the migrations happen in some containerized way, instead of me executing a Prisma command manually in the CLI?\n\nPointing out my misconceptions, hints or feedback is appreciated! Thank you\n\n========================================\n\nTop Answer:\nYou need to run the migration before you start your nextjs app. There are several ways you can do this. Some people do this as part of this CI/CD scripts. In your case of using docker compose, you can change the startup command to run a script that runs the migration before starting up your app.\n\nFirst, create your bash script\n\n```\nnpx prisma migrate deploy\nnpm start\n```\n\nthen change your `Dockerfile` to run the script\n\n```\nCMD [\"startup.sh\"]\n```\n\n========================================\n\nCode:\n```text\nservices:\n  api:\n    build: ./api\n    env_file:\n      - .env\n    volumes:\n      - ./api:/usr/src/app\n    ports:\n      - ${API_PORT}:${API_PORT}\n    command: npm start\n```\n\n```text\n# Latest LTS version\nFROM node:14\n\n# Set default values for environment variables\nENV API_PORT=3001\n\n# Create app directory\nWORKDIR /usr/src/app\n\n# Install app dependencies\nCOPY package*.json ./\nRUN npm install\n\n# Bundle app source\nCOPY . .\n\n# Bind port\nEXPOSE ${API_PORT}\n\n# Start server\nCMD [\"npm\", \"start\"]\n```\n\n```text\napollo-server-express\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nDockerfile\n```\n\n```yaml\nversion: '3'\nservices:\n  prisma-migrate:\n    container_name: prisma-migrate\n    build: ./api/prisma\n    env_file:\n      - .env\n    environment:\n      DB_HOST: <secret>\n    depends_on:\n      - db\n\n  db:\n    image: postgres:13\n    container_name: db\n    restart: always\n    env_file:\n      - .env\n    environment:\n      DB_PORT: 5432\n    ports:\n      - ${DB_PORT}:5432\n    volumes:\n      - ${POSTGRES_VOLUME_DIR}:/var/lib/postgresql/data\n```\n\n```text\nFROM node:14\n\nRUN echo $DATABASE_URL\n\nWORKDIR /app\n\nCOPY ./package.json ./\nCOPY . ./prisma/\n\nRUN chmod +x ./prisma/wait-for-postgres.sh\n\nRUN npm install\nRUN npx prisma generate\n\nRUN apt update\nRUN apt --assume-yes install postgresql-client\n\n# Git will replace the LF line-endings with CRLF, causing issues while executing the wait-for-postgres shell script\n# Install dos2unix and replace CRLF (\\r\\n) newlines with LF (\\n)\nRUN apt --assume-yes install dos2unix\nRUN dos2unix ./prisma/wait-for-postgres.sh\n\nCMD sh ./prisma/wait-for-postgres.sh ${DB_HOST} ${POSTGRES_USER} npx prisma migrate deploy && npx prisma db seed --preview-feature\n```\n\n```sh\n#!/bin/sh\n# wait-for-postgres.sh\n\nset -e\n  \nhost=\"$1\"\nuser=\"$2\"\nshift\nshift\ncmd=\"$@\"\n  \nuntil PGPASSWORD=$POSTGRES_PASSWORD psql -h \"$host\" -U \"$user\" -c '\\q'; do\n  >&2 echo \"Postgres is unavailable - sleeping\"\n  sleep 1\ndone\n  \n>&2 echo \"Postgres is up - executing command\"\n\nexec $cmd\n```\n\n```text\n# ---- DB ----\nDB_HOST=localhost\nDB_PORT=5432\nDB_SCHEMA=example\n\nPOSTGRES_DB=example\nPOSTGRES_USER=example\nPOSTGRES_VOLUME_DIR=/path/where/you/want/to/store\nPOSTGRES_PASSWORD=example\n\nDATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}\n```\n\n```text\ndocker-compose.migrate.yml\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\ndocker-compose.migrate.yml\n```\n\n```text\nwait-for-postgres.sh\n```\n\n```text\n.env\n```\n\n```sh\nnpx prisma migrate deploy\nnpm start\n```\n\n```text\nCMD [\"startup.sh\"]\n```\n\n```text\nDockerfile\n```\n\n========================================\n\nComments:\n- Thanks @Athir ! I ended up creating a second compose file: `docker-compose.migrate.yml` and indeed run this as part of my CI/CD now. This is a viable alternative.\n- @MaxdeKrieger could you please more details on your new docker compose?\n- @igo I posted my answer below now, let me know if you need more details\n- Can you please show the `wait-for-postgres.sh` script as well?\n- @mrodo Done, I've now edited the answer and added the `wait-for-postgres.sh` script.\n- Hello @MaxdeKrieger, please complete your answer by admin a sample `.env`.\n- @KasirBarati sorry for the late reply, did it now :)","metadata":{"transformedAt":"2026-08-18T18:33:14.838Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":256,"estimatedTokens":1267}}220{"id":"stack-68140035","source":"stackoverflow","questionId":68140035,"title":"Exclude user's password from query with Prisma 2","tags":["node.js","rest","prisma","prisma2"],"text":"Title: Exclude user's password from query with Prisma 2\nTags: node.js, rest, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nRecently I started working on a new project to learn some new technologies (Prisma 2, REST api with Express, etc.). Tho, I faced a problem.\n\nMy app has a user authentication system and the user model has a password column. So, when the client requests a user, the backend selects all the columns from the database including the password (that's hashed by the way).\n\nI tried to not select the password column on the prisma findMany, like this:\n\n```\nawait prisma.user.findUnique({\n where: {\n ...\n },\n select: {\n password: false\n }\n});\n```\n\nBut I got an error by prisma saying that the select should contain at least one truly value. Thus, I added `id: true` to the select. I made an api request and I saw that only the id was returning for the user.\n\nBy my understanding, prisma expects me to add all the columns I care to the select object. But, I need a lot of columns from the user and I am making a lot of queries to fetch users and I cannot just write all the field I need everytime.\n\nSo, I wanted to ask you if there is a legit way to do that.\n\nPS: I don't take \"use rawQuery instead\" as a solution.\n\n========================================\n\nTop Answer:\nI'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.\n\n```\nimport { PrismaClient } from '@prisma/client'\n\nasync function excludePasswordMiddleware(params, next) {\n const result = await next(params)\n if (params?.model === 'User' && params?.args?.select?.password !== true) {\n delete result.password\n }\n return result\n}\n\nconst prisma = new PrismaClient()\nprisma.$use(excludePasswordMiddlware)\n```\n\nThis 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:\n\n```\nasync validateUser(email: string, password: string) {\n const user = await this.prisma.user.findUnique({\n where: { email },\n select: {\n emailVerified: true,\n password: true,\n },\n })\n // Continue to validate user, compare passwords, etc.\n return isValid\n}\n```\n\n========================================\n\nCode:\n```js\nawait prisma.user.findUnique({\n  where: {\n    ...\n  },\n  select: {\n    password: false\n  }\n});\n```\n\n```text\nid: true\n```\n\n```text\nplainToClass\n```\n\n```text\ncolumn: true\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n\nasync function excludePasswordMiddleware(params, next) {\n  const result = await next(params)\n  if (params?.model === 'User' && params?.args?.select?.password !== true) {\n    delete result.password\n  }\n  return result\n}\n\nconst prisma = new PrismaClient()\nprisma.$use(excludePasswordMiddlware)\n```\n\n```js\nasync validateUser(email: string, password: string) {\n  const user = await this.prisma.user.findUnique({\n    where: { email },\n    select: {\n      emailVerified: true,\n      password: true,\n    },\n  })\n  // Continue to validate user, compare passwords, etc.\n  return isValid\n}\n```\n\n```text\nUser\n```\n\n```text\nfunction exclude(user, ...keys) {\n  for (let key of keys) {\n    delete user[key]\n  }\n  return user\n}\n\nfunction main() {\n  const user = await prisma.user.findUnique({ where: 1 })\n  const userWithoutPassword = exclude(user, 'password')\n}\n```\n\n```js\npost.author[\"password\"] = \"_\"; // {hack} obfuscate the password\n```\n\n```js\nimport { Prisma } from '@prisma/client';\n\ntype A<T extends string> = T extends `${infer U}ScalarFieldEnum` ? U : never;\ntype Entity = A<keyof typeof Prisma>;\ntype Keys<T extends Entity> = Extract<\n  keyof (typeof Prisma)[keyof Pick<typeof Prisma, `${T}ScalarFieldEnum`>],\n  string\n>;\n\nexport function prismaExclude<T extends Entity, K extends Keys<T>>(\n  type: T,\n  omit: K[],\n) {\n  type Key = Exclude<Keys<T>, K>;\n  type TMap = Record<Key, true>;\n  const result: TMap = {} as TMap;\n  for (const key in Prisma[`${type}ScalarFieldEnum`]) {\n    if (!omit.includes(key as K)) {\n      result[key as Key] = true;\n    }\n  }\n  return result;\n}\n```\n\n```js\nasync findById(id: string) {\n    const user = await this.prisma.user.findUniqueOrThrow({\n      where: { id },\n      select: prismaExclude('User', ['password']),\n    });\n    return user;\n  }\n```\n\n```text\nconst prisma = new PrismaClient({...}).$extends({\n   model: {\n    $allModels: {\nasync findUniqueExcept<Model, Args>(\n          this: Model,\n          args: PrismaType.Exact<Args, PrismaType.Args<Model, 'findUnique'>>,\n          excepts: Record<string, boolean>\n        ): Promise<PrismaType.Result<Model, Args, 'findUnique'>> {\n\n            const data = await (this as any).findUnique(args)\n\n            for(let column of Object.keys(excepts)){\n              if(column in data && excepts[column] === false){\n                delete data[column]\n              }else{\n                new Error('Except values should be false.')\n              }\n            }\n\n            return data\n          }\n      }\n  } \n})\n```\n\n```text\nawait prisma.user.findUniqueExcept({\n    where: {\n      email: email\n    },\n  }, { password: false })\n// returns everything without password\n```\n\n```text\n$extends\n```\n\n```text\npassword\n```\n\n```js\n// Exclude keys from an object\nexport function excludeFromObject<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n  return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key as K))) as Omit<T, K>\n}\n\n// Exclude keys from objects in a list\nexport function excludeFromList<T, K extends keyof T>(objects: T[], keysToDelete: K[]): Omit<T, K>[] {\n  return objects.map((obj) => excludeFromObject(obj, keysToDelete)) as Omit<T, K>[]\n}\n```\n\n```js\nasync findAll() {\n    const allItems = await this.prisma.user.findMany()\n\n    return excludeFromList(allItems, ['password'])\n  }\n\n  async findOne(id: number) {\n    const foundItem = await this.prisma.user.findUnique({\n      where: {\n        id,\n      },\n    })\n\n    return excludeFromObject(foundItem, ['password'])\n  }\n```\n\n```text\nexclude\n```\n\n```text\nconst { password, ...userWithoutPassword } = user;\nres.status(200).json({\n    success: true,\n    data: userWithoutPassword,\n});\n```\n\n```js\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"omitApi\"] // Add this line\n}\n\nmodel User {\n  id        Int      @id @default(autoincrement())\n  firstName String\n  password    String\n }\n```\n\n```js\n// The password field is excluded on all query on the user model\nconst prisma = new PrismaClient({\n  omit: {\n    user: {\n      password: true\n    }\n  }\n})\n```\n\n```js\nconst prisma = new PrismaClient()\n\n// The password field is excluded only in this query\nconst user = await prisma.user.findUnique({\n  omit: {\n    password: true\n  },\n  where: { \n    id: 1 \n  } \n})\n```\n\n```text\nnpx prisma generate\n```\n\n```text\ngenerator client {\n  previewFeatures = [\"omitApi\"]\n}\n```\n\n```text\nconst user = await prisma.user.findUnique({\n  omit: {\n    password: true\n  },\n  where: ...\n})\n```\n\n```text\nconst prisma = new PrismaClient({\n  omit: {\n    user: {\n      password: true\n    }\n  }\n})\n```\n\n```text\nomitApi\n```\n\n```text\nDTO class\n```\n\n```text\nclass-validator\n```\n\n```text\nPOST\n```\n\n```text\nPUT\n```\n\n```text\n@Body\n```\n\n```text\nplainToInstance\n```\n\n```text\nclass-transformer\n```\n\n```text\nplainToInstance\n```\n\n========================================\n\nComments:\n- Actually, I think the most efficient way to do it (especially in case you are using this as an API response) is to use class-transformer. With it, you can create a DTO class for the user, that doesn't expose, for example, the password field. Then, use the `plainToClass` function to convert the user entity (that comes from Prisma and includes the password) to the user DTO class (that doesn't include the user's password). That's how you get rid of the password. Check the library it's pretty cool, it made things a lot simpler for me.\n- Useful. Only thing I would add to this is that is doesn't cover cases where more than one user object is returned from methods like findMany(). Checking if the result is an array would then cover most use cases: if(Array.isArray(result)) { result = result.map(user => { delete user.password; return user; }); }\n- Just a side note for new dev who read this answer: this is technically a really bad idea though it's the most straight forward way to do it, and from the official website. You have to always remember to exclude the password column all the time, so it's a huge potential data leak issue as well as for all the relation query cases. Using for loop also causes performance issue unnecessarily. The ideal way to solve it is actually exclude it in the SQL level or Prisma model level. That's what the original question is looking for. In this discussion: github.com/prisma/prisma/issues/5042\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- If I implemented PrismaClient like a class: @Injectable() export class DatabaseService extends PrismaClient implements OnModuleInit { async onModuleInit() { await this.$connect(); } } how can I use it globaly?\n- @SajjadHoviegar ``` constructor() { super({ omit: { user: { // make sure that password is never queried. password: true, }, }, }) } ``` Make sure your prisma is at least `5.16.0`","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":377,"estimatedTokens":2428}}221{"id":"stack-71663204","source":"stackoverflow","questionId":71663204,"title":"Docker Prisma Error P1001: Can't reach database server at `postgres`:`5432`","tags":["node.js","postgresql","docker","express","prisma"],"text":"Title: Docker Prisma Error P1001: Can't reach database server at `postgres`:`5432`\nTags: node.js, postgresql, docker, express, prisma\nSource: Stack Overflow\n\nQuestion:\nAfter hours of searchs, I must bow dow and ask you some advices on my problem :\n\nMy backend (express + prisma + postgresql) is Dockerized, functionning BUT I can't use `npx prisma` commands from my wsl2 zsh terminal.\n\nHere is my .env\n\n```\n# Database settings\nNODE_ENV=dev\nDB_USER=user\nDB_PASS=password\nDATABASE_URL=\"postgresql://${DB_USER}:${DB_PASS}@postgres/chimere?schema=public\"\n```\n\nDockerfile :\n\n```\nFROM node:17-alpine3.14 as base\n\nWORKDIR /user/src/app\nCOPY package*.json /user/src/app/\nEXPOSE 5000\n\nFROM base as dev\nENV NODE_ENV=development\nRUN npm install -g nodemon && npm install\nCOPY . /user/src/app/\nRUN npx prisma generate\nCMD [\"nodemon\", \"src/index.js\"]\n\nFROM base as production\nENV NODE_ENV=production\nRUN npm ci\nCOPY . /user/src/app/\nRUN npx prisma generate\nCMD [\"node\", \"src/index.js\"]\n```\n\ndocker-compose.yml :\n\n```\nversion: '3.8'\nservices:\n postgres:\n image: postgres\n restart: always\n environment:\n - POSTGRES_USER=${DB_USER}\n - POSTGRES_PASSWORD=${DB_PASS}\n volumes:\n - postgres:/var/lib/postgresql/data\n ports:\n - '5432:5432'\n web:\n build:\n context: ./\n target: dev\n restart: always\n volumes:\n - .:/usr/src/app\n - uploaded-files:/usr/src/app/public/media/files\n - uploaded-pictures:/usr/src/app/public/media/pictures\n command: npm run start:dev\n ports:\n - \"5000:5000\"\n environment:\n NODE_ENV: development\n DEBUG: nodejs-docker-express:*\n\nvolumes:\n postgres:\n uploaded-files:\n uploaded-pictures:\n```\n\nand Prisma Schema :\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n binaryTargets = [\"native\", \"linux-musl\"]\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n```\n\nLike you can see I'm prettry new to Docker and almost everything is an adjusted copypasta from Google (:\n\nHow can I get my app to work AND get my commands to work aswell ?\n\nThanks !\n\n========================================\n\nTop Answer:\nYou need to act from inside the container.\n\nFirst, create an interactive shell in the container using docker exec:\n\n```\ndocker exec -it sh\n```\n\n*Note:* the `-i` flag keeps input open to the container, and the `-t` flag creates a pseudo-terminal that the shell can attach to.\n\nThen, once inside the container, execute the commands you need:\n\n```\nnpx prisma migrate dev --name \n```\n\n========================================\n\nCode:\n```text\n# Database settings\nNODE_ENV=dev\nDB_USER=user\nDB_PASS=password\nDATABASE_URL=\"postgresql://${DB_USER}:${DB_PASS}@postgres/chimere?schema=public\"\n```\n\n```text\nFROM node:17-alpine3.14 as base\n\nWORKDIR /user/src/app\nCOPY package*.json /user/src/app/\nEXPOSE 5000\n\nFROM base as dev\nENV NODE_ENV=development\nRUN npm install -g nodemon && npm install\nCOPY . /user/src/app/\nRUN npx prisma generate\nCMD [\"nodemon\", \"src/index.js\"]\n\nFROM base as production\nENV NODE_ENV=production\nRUN npm ci\nCOPY . /user/src/app/\nRUN npx prisma generate\nCMD [\"node\", \"src/index.js\"]\n```\n\n```text\nversion: '3.8'\nservices:\n  postgres:\n    image: postgres\n    restart: always\n    environment:\n      - POSTGRES_USER=${DB_USER}\n      - POSTGRES_PASSWORD=${DB_PASS}\n    volumes:\n      - postgres:/var/lib/postgresql/data\n    ports:\n      - '5432:5432'\n  web:\n      build:\n        context: ./\n        target: dev\n      restart: always\n      volumes:\n        - .:/usr/src/app\n        - uploaded-files:/usr/src/app/public/media/files\n        - uploaded-pictures:/usr/src/app/public/media/pictures\n      command: npm run start:dev\n      ports:\n        - \"5000:5000\"\n      environment:\n        NODE_ENV: development\n        DEBUG: nodejs-docker-express:*\n\nvolumes:\n    postgres:\n    uploaded-files:\n    uploaded-pictures:\n```\n\n```text\ngenerator client {\n    provider      = \"prisma-client-js\"\n    binaryTargets = [\"native\", \"linux-musl\"]\n}\n\ndatasource db {\n    provider = \"postgresql\"\n    url      = env(\"DATABASE_URL\")\n}\n```\n\n```text\nnpx prisma\n```\n\n```text\nDATABASE_URL=\"mysql://${DB_USER}:${DB_PASS}@localhost:3306/project_name\"\n```\n\n```yaml\nversion: '3.1'\n\nservices:\n\n  db:\n    image: mysql\n    container_name: mysql\n    ports:\n      - 3306:3306\n```\n\n```text\nDATABASE_URL=\"mysql://${DB_USER}:${DB_PASS}@mysql:3306/project_name\"\n```\n\n```yaml\nversion: '3.8'\nservices:\n  postgres:\n    image: postgres\n    container_name: postgres\n    restart: always\n    environment:\n      - POSTGRES_USER=${DB_USER}\n      - POSTGRES_PASSWORD=${DB_PASS}\n    volumes:\n      - postgres:/var/lib/postgresql/data\n    ports:\n      - '5432:5432'\n```\n\n```text\nDATABASE_URL=\"postgresql://${DB_USER}:${DB_PASS}@{container_name}/chimere?schema=public\"\n```\n\n```text\nmysql\n```\n\n```text\nDATABASE_URL\n```\n\n```text\n.env\n```\n\n```text\nlocalhost\n```\n\n```text\nlocalhost\n```\n\n```text\ncontainer_name\n```\n\n```text\n.env\n```\n\n```text\n.env\n```\n\n```bash\ndocker exec -it <name of your containter> sh\n```\n\n```bash\nnpx prisma migrate dev --name <name of your migration>\n```\n\n```text\n-i\n```\n\n```text\n-t\n```\n\n========================================\n\nComments:\n- The database host name will be different if you're running it from within the Compose setup (`postgres`) or from outside a container (`localhost`); you'll need different environment-variable settings to describe the different environments.\n- Hey, thanks for the reply. Could you please elaborate or give me an example, I'm a bit lost with Docker :/\n- Thanks for providing this solution! Would never thought that container name is going to be used/replaced in connection string\n- damn weird this thing, thanks man\n- Would this be run in the dockerfile i.e. a line `npx prisma migrate dev`? I have a make sure your database is running issue, although my container is up and generate has been run... is it that i would also need to migrate (in the container).","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":299,"estimatedTokens":1449}}222{"id":"stack-71183677","source":"stackoverflow","questionId":71183677,"title":"When I run nest.js, I get a Missing \"driver\" option error","tags":["graphql","nestjs","prisma"],"text":"Title: When I run nest.js, I get a Missing \"driver\" option error\nTags: graphql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using nest.js, prisma, and graphql.\n\nWhen I run the npm run start:dev command, I get an error.\n\nIf anyone knows how to solve this, please let me know.\n\nERROR [GraphQLModule] Missing\n\"driver\" option. In the latest version of \"@nestjs/graphql\" package\n(v10) a new required configuration property called \"driver\" has been\nintroduced. Check out the official documentation for more details on\nhow to migrate (https://docs.nestjs.com/graphql/migration-guide).\nExample:\n\nGraphQLModule.forRoot({\ndriver: ApolloDriver,\n})\n\n```\napp.module.ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\nimport { DonationsModule } from './donations/donations.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: false,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```\ngenerate-typings.ts\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n typePaths: ['./src/**/*.graphql'],\n path: join(process.cwd(), 'src/graphql.ts'),\n outputAs: 'class',\n watch: true,\n});\n```\n\nfix\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n driver: ApolloDriver,\n autoSchemaFile: true,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n========================================\n\nTop Answer:\nAlso don't forget to import\n\n```\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\n```\n\n========================================\n\nCode:\n```text\napp.module.ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\nimport { DonationsModule } from './donations/donations.module';\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      playground: false,\n      plugins: [ApolloServerPluginLandingPageLocalDefault()],\n      typePaths: ['./**/*.graphql'],\n    }),\n    DonationsModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\ngenerate-typings.ts\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n  typePaths: ['./src/**/*.graphql'],\n  path: join(process.cwd(), 'src/graphql.ts'),\n  outputAs: 'class',\n  watch: true,\n});\n```\n\n```text\n@Module({\n  imports: [\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n      autoSchemaFile: true,\n      plugins: [ApolloServerPluginLandingPageLocalDefault()],\n      typePaths: ['./**/*.graphql'],\n    }),\n    DonationsModule,\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\n```\n\n```text\n@Module({\n  imports: [\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n    }),\n  ],\n})\n```\n\n```text\nGraphQLModule\n```\n\n```text\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\n```\n\n========================================\n\nComments:\n- I rewrote it as above. (fix) The following error occurs at the location import { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';.\n- Cannot find module '@nestjs/apollo' or corresponding type declaration. ts(2307)\n- Have you installed @nestjs/apollo? @yuturo","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":168,"estimatedTokens":993}}223{"id":"stack-67864559","source":"stackoverflow","questionId":67864559,"title":"Prisma.js: We found changes that cannot be executed","tags":["node.js","express","orm","prisma","prisma2"],"text":"Title: Prisma.js: We found changes that cannot be executed\nTags: node.js, express, orm, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI've used prisma.js as an ORM in my project.\n\nAfter executing the `npx prisma migrate dev --name rename_and_add_some_columns`,\nI got this error:\n\nWe found changes that cannot be executed\n\nError Details:\n\nStep 1 Added the required column `CategoryId` to the `Post` table\nwithout a default value. There are 2 rows in this table, it is not\npossible to execute this step. • Step 1 Added the required column\n`ModifiedDate` to the `Post` table without a default value. There are\n2 rows in this table, it is not possible to execute this step. •\nStep 2 Added the required column `ModifiedDate` to the `Profile` table\nwithout a default value. There are 1 rows in this table, it is not\npossible to execute this step. • Step 4 Added the required column\n`ModifiedDate` to the `User` table without a default value. There are\n2 rows in this table, it is not possible to execute this step.\n\nYou can use prisma migrate dev --create-only to create the migration\nfile, and manually modify it to address the underlying issue(s). Then\nrun prisma migrate dev to apply it and verify it works.\n\nHow can I solve it?\n\n// This is my Prisma schema file,\n\n```\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Category {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @updatedAt\n Title String @db.VarChar(50)\n IsActive Boolean\n Posts Post[]\n}\n\nmodel Post {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @updatedAt\n Title String @db.VarChar(255)\n Description String?\n IsPublished Boolean @default(false)\n IsActive Boolean @default(true)\n IsActiveNewComment Boolean @default(true)\n Author User @relation(fields: [AuthorId], references: [Id])\n AuthorId Int\n Comment Comment[]\n Tag Tag[] @relation(\"TagToPost\", fields: [tagId], references: [Id])\n tagId Int?\n Category Category @relation(fields: [CategoryId], references: [Id])\n CategoryId Int\n}\n\nmodel User {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @updatedAt\n Email String @unique\n Name String?\n Posts Post[]\n Profile Profile?\n Comments Comment[]\n}\n\nmodel Profile {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @updatedAt\n Bio String?\n User User @relation(fields: [UserId], references: [Id])\n UserId Int @unique\n}\n\nmodel Comment {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @updatedAt\n Comment String\n WrittenBy User @relation(fields: [WrittenById], references: [Id])\n WrittenById Int\n Post Post @relation(fields: [PostId], references: [Id])\n PostId Int\n}\n\nmodel Tag {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @updatedAt\n Title String @unique\n Posts Post[] @relation(\"TagToPost\")\n}\n```\n\n========================================\n\nTop Answer:\nAlternatively, you can just add `@default(now())` to your `ModifiedDate` properties. So, for instance, the `Category` model would be:\n\n```\nmodel Category {\n Id Int @id @default(autoincrement())\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime @default(now()) @updatedAt\n Title String @db.VarChar(50)\n IsActive Boolean\n Posts Post[]\n}\n```\n\n========================================\n\nCode:\n```text\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Category {\n  Id           Int      @id @default(autoincrement())\n  CreatedDate  DateTime @default(now())\n  ModifiedDate DateTime @updatedAt\n  Title        String   @db.VarChar(50)\n  IsActive     Boolean\n  Posts        Post[]\n}\n\nmodel Post {\n  Id                 Int       @id @default(autoincrement())\n  CreatedDate        DateTime  @default(now())\n  ModifiedDate       DateTime  @updatedAt\n  Title              String    @db.VarChar(255)\n  Description        String?\n  IsPublished        Boolean   @default(false)\n  IsActive           Boolean   @default(true)\n  IsActiveNewComment Boolean   @default(true)\n  Author             User      @relation(fields: [AuthorId], references: [Id])\n  AuthorId           Int\n  Comment            Comment[]\n  Tag                Tag[]     @relation(\"TagToPost\", fields: [tagId], references: [Id])\n  tagId              Int?\n  Category           Category  @relation(fields: [CategoryId], references: [Id])\n  CategoryId         Int\n}\n\nmodel User {\n  Id           Int       @id @default(autoincrement())\n  CreatedDate  DateTime  @default(now())\n  ModifiedDate DateTime  @updatedAt\n  Email        String    @unique\n  Name         String?\n  Posts        Post[]\n  Profile      Profile?\n  Comments     Comment[]\n}\n\nmodel Profile {\n  Id           Int      @id @default(autoincrement())\n  CreatedDate  DateTime @default(now())\n  ModifiedDate DateTime @updatedAt\n  Bio          String?\n  User         User     @relation(fields: [UserId], references: [Id])\n  UserId       Int      @unique\n}\n\nmodel Comment {\n  Id           Int      @id @default(autoincrement())\n  CreatedDate  DateTime @default(now())\n  ModifiedDate DateTime @updatedAt\n  Comment      String\n  WrittenBy    User     @relation(fields: [WrittenById], references: [Id])\n  WrittenById  Int\n  Post         Post     @relation(fields: [PostId], references: [Id])\n  PostId       Int\n}\n\nmodel Tag {\n  Id           Int      @id @default(autoincrement())\n  CreatedDate  DateTime @default(now())\n  ModifiedDate DateTime @updatedAt\n  Title        String   @unique\n  Posts        Post[]   @relation(\"TagToPost\")\n}\n```\n\n```text\nnpx prisma migrate dev --name rename_and_add_some_columns\n```\n\n```text\nCategoryId\n```\n\n```text\nPost\n```\n\n```text\nModifiedDate\n```\n\n```text\nPost\n```\n\n```text\nModifiedDate\n```\n\n```text\nProfile\n```\n\n```text\nModifiedDate\n```\n\n```text\nUser\n```\n\n```text\nmigrate\n```\n\n```text\n?\n```\n\n```text\n@updatedAt\n```\n\n```text\nmodel Category {\n  Id           Int       @id @default(autoincrement())\n  CreatedDate  DateTime  @default(now())\n  ModifiedDate DateTime? @updatedAt\n  Title        String    @db.VarChar(50)\n  IsActive     Boolean\n  Posts        Post[]\n}\n\nmodel Post {\n  Id                 Int       @id @default(autoincrement())\n  CreatedDate        DateTime  @default(now())\n  ModifiedDate       DateTime? @updatedAt\n  Title              String    @db.VarChar(255)\n  Description        String?\n  IsPublished        Boolean   @default(false)\n  IsActive           Boolean   @default(true)\n  IsActiveNewComment Boolean   @default(true)\n  Author             User      @relation(fields: [AuthorId], references: [Id])\n  AuthorId           Int\n  Comment            Comment[]\n  Tag                Tag[]     @relation(\"TagToPost\", fields: [tagId], references: [Id])\n  tagId              Int?\n  Category           Category? @relation(fields: [CategoryId], references: [Id])\n  CategoryId         Int?\n}\n\nmodel User {\n  Id           Int       @id @default(autoincrement())\n  CreatedDate  DateTime  @default(now())\n  ModifiedDate DateTime? @updatedAt\n  Email        String    @unique\n  Name         String?\n  Posts        Post[]\n  Profile      Profile?\n  Comments     Comment[]\n}\n\nmodel Profile {\n  Id           Int       @id @default(autoincrement())\n  CreatedDate  DateTime  @default(now())\n  ModifiedDate DateTime? @updatedAt\n  Bio          String?\n  User         User      @relation(fields: [UserId], references: [Id])\n  UserId       Int       @unique\n}\n\nmodel Comment {\n  Id           Int       @id @default(autoincrement())\n  CreatedDate  DateTime  @default(now())\n  ModifiedDate DateTime? @updatedAt\n  Comment      String\n  WrittenBy    User      @relation(fields: [WrittenById], references: [Id])\n  WrittenById  Int\n  Post         Post      @relation(fields: [PostId], references: [Id])\n  PostId       Int\n}\n\nmodel Tag {\n  Id           Int       @id @default(autoincrement())\n  CreatedDate  DateTime  @default(now())\n  ModifiedDate DateTime? @updatedAt\n  Title        String    @unique\n  Posts        Post[]    @relation(\"TagToPost\")\n}\n```\n\n```text\nCategory\n```\n\n```text\nCategory?\n```\n\n```text\nInt\n```\n\n```text\nInt?\n```\n\n```text\nDatetime\n```\n\n```text\nDatetime?\n```\n\n```text\nmodel Category {\n  Id           Int      @id @default(autoincrement())\n  CreatedDate  DateTime @default(now())\n  ModifiedDate DateTime @default(now()) @updatedAt\n  Title        String   @db.VarChar(50)\n  IsActive     Boolean\n  Posts        Post[]\n}\n```\n\n```text\n@default(now())\n```\n\n```text\nModifiedDate\n```\n\n```text\nCategory\n```\n\n```text\nmodel MyModel {\n...\n    createdAt   DateTime  @default(now())\n    updatedAt   DateTime? @updatedAt\n}\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nnow()\n```\n\n```text\ncreatedAt\n```\n\n```text\n?\n```\n\n```text\nDateTime?\n```\n\n```text\nupdatedAt\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- Why should I do step 3 (Remove the optional (?) from the field)? Without doing it, it works.\n- If you want it to be required, if not then it's totally fine.","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":418,"estimatedTokens":2289}}224{"id":"stack-74157774","source":"stackoverflow","questionId":74157774,"title":"How to type a variable for a Prisma select property","tags":["typescript","prisma"],"text":"Title: How to type a variable for a Prisma select property\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI’m looking for a way to define a Prisma select statement and then use it in multiple places. For example:\n\n```\nconst userSelect: Prisma.UserSelect = {\n id: true,\n name: true,\n}\n\nconst user = await prisma.user.findUnique({\n where: { id: 1 },\n select: userSelect\n})\n\nconst posts = await prisma.post.findMany({\n where: { authorId: 1 },\n select: {\n id: true,\n user: {\n select: userSelect\n }\n }\n})\n```\n\nHowever, this isn’t working properly. When using `userSelect` in the queries, the queries know `userSelect` is of the expected type `Prisma.UserSelect`, but they don’t know which fields have actually been selected. This ends up typing both `user` and `posts.user` to be `{}`.\n\nA different approach would be to instead write `userSelect` like this:\n\n```\nconst userSelect = {\n id: true,\n name: true,\n} as const;\n```\n\nThat works in the query and correctly types the query result. However, now I lose type safety and autocomplete in the definition of `userSelect`.\n\nCan someone think of a solution that would work correctly in the query select property, the query result, and that would also allow type safety in the definition of the select object?\n\n========================================\n\nTop Answer:\nAn article covering this exact topic was just released by Prisma.\nhttps://www.prisma.io/blog/satisfies-operator-ur8ys8ccq7zb\n\nTo quote from the article:\n\nOne of the most common use cases for the satisfies operator with\nPrisma is to infer the return type of a specific query method like a\nfindUnique — including only the selected fields of a model and its\nrelations.\n\n```\nimport { Prisma } from \"@prisma/client\";\n\n// Create a strongly typed `PostSelect` object with `satisfies`\nconst postSelect = {\n title: true,\n createdAt: true,\n author: {\n name: true,\n email: true,\n },\n} satisfies Prisma.PostSelect;\n\n// Infer the resulting payload type\ntype MyPostPayload = Prisma.PostGetPayload;\n\n// The result type is equivalent to `MyPostPayload | null`\nconst post = await prisma.post.findUnique({\n where: { id: 3 },\n select: postSelect,\n});\n```\n\n========================================\n\nCode:\n```text\nconst userSelect: Prisma.UserSelect = {\n    id: true,\n    name: true,\n}\n\nconst user = await prisma.user.findUnique({\n    where: { id: 1 },\n    select: userSelect\n})\n\nconst posts = await prisma.post.findMany({\n    where: { authorId: 1 },\n    select: {\n        id: true,\n        user: {\n            select: userSelect\n        }\n    }\n})\n```\n\n```text\nconst userSelect = {\n    id: true,\n    name: true,\n} as const;\n```\n\n```text\nuserSelect\n```\n\n```text\nuserSelect\n```\n\n```text\nPrisma.UserSelect\n```\n\n```text\nuser\n```\n\n```text\nposts.user\n```\n\n```text\n{}\n```\n\n```text\nuserSelect\n```\n\n```text\nuserSelect\n```\n\n```text\nconst userSelect = { ... } satisfies Prisma.UserSelect;\n```\n\n```text\nfunction makeUserSelect<T extends Prisma.UserSelect>(t: T): T { return t; }\n\nconst userSelect = makeUserSelect({ ... });\n```\n\n```text\nsatisfies\n```\n\n```text\nuserSelect\n```\n\n```js\nexport const userSelect = {\n    id: true,\n    name: true,\n}\n\nexport type UserSelect = Prisma.UserGetPayload<{ select: typeof useSelect }>\n```\n\n```js\nconst posts = await prisma.post.findMany({\n    where: { authorId: 1 },\n    select: {\n        id: true,\n        user: {\n            select: userSelect\n        }\n    }\n})\n```\n\n```text\nUserSelect\n```\n\n```js\nimport { Prisma } from \"@prisma/client\";\n\n// Create a strongly typed `PostSelect` object with `satisfies`\nconst postSelect = {\n  title: true,\n  createdAt: true,\n  author: {\n    name: true,\n    email: true,\n  },\n} satisfies Prisma.PostSelect;\n\n// Infer the resulting payload type\ntype MyPostPayload = Prisma.PostGetPayload<{ select: typeof postSelect }>;\n\n// The result type is equivalent to `MyPostPayload | null`\nconst post = await prisma.post.findUnique({\n  where: { id: 3 },\n  select: postSelect,\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":209,"estimatedTokens":982}}225{"id":"stack-67070283","source":"stackoverflow","questionId":67070283,"title":"getting error \"SyntaxError Cannot use import statement outside a module\"","tags":["express","prisma"],"text":"Title: getting error \"SyntaxError Cannot use import statement outside a module\"\nTags: express, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Prisma.js in my express app. but I am getting error on module import. I am not sure where am I going wrong.\n\n```\n'use strict';\nvar sql = require('../connection.js');\nimport { PrismaClient } from '@prisma/client';\n//const prisma = new PrismaClient()\n\nclass InvoiceService {\n constructor(){\n\n }\n\n getInvoices(body,query,user){\n \n return new Promise(function (resolve, reject) {\n \n resolve(query);\n });\n }\n}\n\nmodule.exports = {InvoiceService};\n```\n\n========================================\n\nCode:\n```text\n'use strict';\nvar sql = require('../connection.js');\nimport { PrismaClient } from '@prisma/client';\n//const prisma = new PrismaClient()\n\nclass InvoiceService {\n    constructor(){\n\n    }\n\n    getInvoices(body,query,user){\n        \n        return new Promise(function (resolve, reject) {\n            \n            resolve(query);\n        });\n    }\n}\n\nmodule.exports = {InvoiceService};\n```\n\n```text\nconst { PrismaClient } = require('@prisma/client');\n```\n\n========================================\n\nComments:\n- This should be the answer","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":64,"estimatedTokens":298}}226{"id":"stack-77333288","source":"stackoverflow","questionId":77333288,"title":"prisma, unable to get my Enums from @prisma/client","tags":["node.js","prisma","nest"],"text":"Title: prisma, unable to get my Enums from @prisma/client\nTags: node.js, prisma, nest\nSource: Stack Overflow\n\nQuestion:\nI'm using prismaJs as my ORM and i have some enum that i need to use. Right now i have 4 different enums in my schema, when i try to access them with\n\nimport { difficulty } from \"@prisma/client\";\nit gives me this error: Module '\"@prisma/client\"' has no exported member 'difficulty'.\n\nfor some reason i'm able to access the enum type situation, but not the other enums that i have.\nhttps://i.sstatic.net/ToxQW.png\n\nmy other enums:\nhttps://i.sstatic.net/WWQXD.png\n\nI tried to delete the migrations folder and use the command npx prisma migrate dev, but it made no difference.\n\nWhen i access import { $Enums } from \"@prisma/client\"; my $Enums only have the situation enum.\n\npackages versions: \"@prisma/client\": \"^5.3.1\", \"prisma\": \"^5.4.2\", \"@nestjs/common\": \"^10.2.6\", \"@nestjs/core\": \"^10.2.6\".\n\n========================================\n\nTop Answer:\nwhen you use prisma it generates models for themselves and migrations for database\n`npx prisma generate` it generate models for you\n`npx prisma migrate dev` it creates migration\nwhen you write enum it creates migration but until you use it in table models in prisma it doesn't create enum for your working environment when you use this enum inside table column after that you can import enum from prisma client\n\n========================================\n\nCode:\n```text\nnpx prisma generate\n```\n\n```text\nnpx prisma migrate dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":40,"estimatedTokens":374}}227{"id":"stack-70111610","source":"stackoverflow","questionId":70111610,"title":"How do I create a prisma migration with a dictionary data?","tags":["prisma"],"text":"Title: How do I create a prisma migration with a dictionary data?\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI have some dictionary table in my DB schema. E.g. \"EventType\" whth fields \"id\" and \"value\".\n\nThis table have one row:\n\n```\n1 TypeOne\n```\n\nCan I create a prisma migration with sql?\n\n```\nINSERT INTO \"EventType\" (id, value) VALUES (2, 'TypeTwo')\n```\n\n========================================\n\nCode:\n```text\n1    TypeOne\n```\n\n```text\nINSERT INTO \"EventType\" (id, value) VALUES (2, 'TypeTwo')\n```\n\n```text\nnpx prisma migrate dev --create-only\n```\n\n```text\n--create-only\n```\n\n```text\nmigration.sql\n```\n\n```text\nnpx prisma migrate dev\n```\n\n```text\nmigration.sql\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.839Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":49,"estimatedTokens":168}}228{"id":"stack-76707774","source":"stackoverflow","questionId":76707774,"title":"Prisma and Nextjs: content is not updating until re-deploy","tags":["node.js","reactjs","typescript","next.js","prisma"],"text":"Title: Prisma and Nextjs: content is not updating until re-deploy\nTags: node.js, reactjs, typescript, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nHere is the website that I just deployed on **Vercel**. I am building a web application using Prisma and Next.js, and I'm experiencing an issue where the content is not updating in real-time until I manually re-deploy the application. Here's the scenario:\n\n- I have an API endpoint in my Next.js app that fetches data from a Prisma database.\n\n- When I create or update data in the database through the application, the changes are reflected immediately in the development environment, but they are not reflected in the production environment until I re-deploy the application (I have ensured that this is not a caching issue).\n\nThis is how I get my data on the front-end:\n\n`const { data: posts, error } = useSWR(`/api/getPosts`, fetcher, {refreshInterval:1000});`\n\nThis is the API endpoint to post the content :\n\n```\n// Addposts to prisma backend\n\nimport { NextResponse, NextRequest } from 'next/server';\nimport prisma from '../../../prisma/client';\n\n// Function\n\nexport async function POST(request:NextRequest) {\n const data = await request.json();\n const title = data.title;\n const user = await prisma.user.findUnique({\n where: {\n email : data.email\n }\n })\n if (!user){\n // return error\n return NextResponse.json({error: \"User not found\"}, {status: 404})\n }\n\n if (!title){\n // throw error\n return NextResponse.json({error: \"Title is required\"}, {status: 400})\n }\n\n if (title.length > 300){\n return NextResponse.json({error:\"Title should not be more than 300 characters\"}, {status:400});\n }\n const userId = user?.id;\n\n const post = await prisma.post.create({\n data: {\n title,\n userId\n }\n })\n try{\n return NextResponse.json({post},{status:200})\n }catch(error){\n return NextResponse.json({error}, {status:500})\n }\n}\n```\n\nAPI endpoint to get all the posts:\n\n```\nimport { NextRequest, NextResponse } from 'next/server'\nimport prisma from '../../../prisma/client'\nimport { NextApiResponse } from 'next';\n\nexport async function GET(request:NextRequest){\n const posts = await prisma.Post.findMany({\n include: {\n user: true\n },\n orderBy:{\n createdAt: 'desc'\n }\n })\n try{\n // return all the posts\n return NextResponse.json({posts},{status:200})\n }catch(error){\n return NextResponse.json(error, {status:500});\n }\n}\n```\n\nHow can I ensure that the content updates are immediately reflected in the production environment without the need for manual re-deployment?\n\nHere is the link to the GitHub repo.\n\n**UPDATE**\n\n*I am able to make POST request and make changes to the db, I think the problem has to be with the GET request since the data appears to be static even when I refresh the page.*\n\nHere is my Runtime Logs on Vercel:\n\nhttps://i.sstatic.net/XqZDk.png\n\n========================================\n\nTop Answer:\nThis is because your GET handler is not using request, and in production it is statically generated (https://nextjs.org/docs/app/building-your-application/routing/router-handlers). No matter are you using SWR or not - your api handler is plain html, it always remains same, returning same data that was prefetched at build time.\n\n```\nexport const dynamic = \"force-dynamic\";\n```\n\nin GET api handler will solve the issue.\n\n========================================\n\nCode:\n```text\n// Addposts to prisma backend\n\nimport { NextResponse, NextRequest } from 'next/server';\nimport prisma from '../../../prisma/client';\n\n// Function\n\nexport async function POST(request:NextRequest) {\n    const data = await request.json();\n    const title = data.title;\n    const user = await prisma.user.findUnique({\n        where: {\n            email : data.email\n        }\n    })\n    if (!user){\n        // return error\n        return NextResponse.json({error: \"User not found\"}, {status: 404})\n    }\n\n    if (!title){\n        // throw error\n        return NextResponse.json({error: \"Title is required\"}, {status: 400})\n    }\n\n    if (title.length > 300){\n        return NextResponse.json({error:\"Title should not be more than 300 characters\"}, {status:400});\n    }\n    const userId = user?.id;\n\n    const post = await prisma.post.create({\n        data: {\n            title,\n            userId\n        }\n    })\n    try{\n        return NextResponse.json({post},{status:200})\n    }catch(error){\n        return NextResponse.json({error}, {status:500})\n    }\n}\n```\n\n```text\nimport { NextRequest, NextResponse } from 'next/server'\nimport prisma from '../../../prisma/client'\nimport { NextApiResponse } from 'next';\n\n\nexport async function GET(request:NextRequest){\n    const posts = await prisma.Post.findMany({\n        include: {\n            user: true\n        },\n        orderBy:{\n            createdAt: 'desc'\n        }\n    })\n    try{\n        // return all the posts\n        return NextResponse.json({posts},{status:200})\n    }catch(error){\n        return NextResponse.json(error, {status:500});\n    }\n}\n```\n\n```text\nconst { data: posts, error } = useSWR(`/api/getPosts`, fetcher, {refreshInterval:1000});\n```\n\n```text\naxios.get(url/api/getPosts)\n```\n\n```text\naxios.post(url/api/addPosts)\n```\n\n```text\naxios.get(url/api/Posts)\n```\n\n```text\naxios.post(url/api/Posts)\n```\n\n```text\nexport const dynamic = \"force-dynamic\";\n```\n\n```text\nexport const revalidate = 1\n```\n\n========================================\n\nComments:\n- Good catch, well done. Upvoted.\n- I have updated my answer with comments on your solution.","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":215,"estimatedTokens":1361}}229{"id":"stack-67894860","source":"stackoverflow","questionId":67894860,"title":"Explicit many to many relation prisma","tags":["javascript","relationship","prisma","prisma2"],"text":"Title: Explicit many to many relation prisma\nTags: javascript, relationship, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI have these 3 prisma models,\n\n```\nmodel user {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @default(now())\n courses userOnCourse[]\n}\n\nmodel course {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @default(now())\n users userOnCourse[]\n title String\n description String\n}\n\nmodel userOnCourse {\n createdAt DateTime @default(now())\n user user @relation(fields: [userId], references: [id])\n userId String\n course Course @relation(fields: [courseId], references: [id])\n courseId String\n\n @@id([userId, courseId])\n}\n```\n\nIt's a many-to-many relation where one user can have many courses and one course can have many users, for referencing the explicit m-m relation I created another model names **userOnCourse**.\n\nI am struggling to pass the reference of courseId into the userOnCourse model, I want to connect the course in conjunction with userid into that model but as it's created on runtime it seems not possible to pass the courseId on compile time.\n\nHere is the code, Assume we already have user data when creating a course, How to pass the courseId that has been creating on run-time, and make a connection.\n\nI am following this reference from prisma docs.\n\n```\nconst createCourse = await prisma.course.create({\n data: {\n title: courseData.title,\n description: courseData.description,\n users: {\n connect: {\n userId_courseId: {\n userId: user.id,\n courseId: ?? // That is where the problem is, how can i add the coursesId?\n },\n },\n },\n },\n });\n```\n\n========================================\n\nTop Answer:\nIn case you need to assign already existing entity:\n\n```\nconst response: course = await prisma.course.create(\n { data: \n { ...someOtherData, \n userOnCourse: { create: [ {user: { connect: { id: 2 } } } ]}\n } \n }\n );\n```\n\nIt's confusing since it says create but it means to create a connection with an already existing entity.\n\n========================================\n\nCode:\n```text\nmodel user {\n  id                        String                 @id @default(cuid())\n  createdAt                 DateTime               @default(now())\n  updatedAt                 DateTime               @default(now())\n  courses                   userOnCourse[]\n}\n\nmodel course {\n  id                      String                         @id @default(cuid())\n  createdAt               DateTime                       @default(now())\n  updatedAt               DateTime                       @default(now())\n  users                   userOnCourse[]\n  title                   String\n  description             String\n}\n\nmodel userOnCourse {\n  createdAt     DateTime    @default(now())\n  user          user        @relation(fields: [userId], references: [id])\n  userId        String\n  course        Course      @relation(fields: [courseId], references: [id])\n  courseId      String\n\n  @@id([userId, courseId])\n}\n```\n\n```text\nconst createCourse = await prisma.course.create({\n            data: {\n                title: courseData.title,\n                description: courseData.description,\n                users: {\n                    connect: {\n                        userId_courseId: {\n                            userId: user.id,\n                            courseId: ?? // That is where the problem is, how can i add the coursesId?\n                        },\n                    },\n                },\n            },\n        });\n```\n\n```text\nawait prisma.course.create({\n    data: {\n      description: 'des',\n      title: 'title',\n      users: { create: { userId: user.id } },\n    },\n})\n```\n\n```text\ncreate\n```\n\n```text\nconnect\n```\n\n```text\nUser\n```\n\n```text\nCourse\n```\n\n```text\ncreate\n```\n\n```text\nconst response: course = await prisma.course.create(\n            { data: \n                { ...someOtherData, \n                    userOnCourse: { create: [ {user: { connect: { id: 2 } } } ]}\n                }  \n            }\n        );\n```\n\n========================================\n\nComments:\n- Thank you :) It did work. It automatically created the right id for that in the required DB.\n- Wow, this is incredibly confusing and their documentation is very lacking.","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":170,"estimatedTokens":1065}}230{"id":"stack-78473636","source":"stackoverflow","questionId":78473636,"title":"How can I generate Prisma CUID's when using sql?","tags":["javascript","sql","postgresql","prisma"],"text":"Title: How can I generate Prisma CUID's when using sql?\nTags: javascript, sql, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a Prisma ORM server for my database. I am trying to use the `cuid()` function outside of the prisma schema.prisma file, but I don't see any package that imports that function and I don't know where it comes from. I want change the format of a table and I'm in the process of migrating the data from one format to another by making different tables (one with the original data and one with the newly formatted data). Currently, I use an approach using prisma queries to get the data I need, but I want to try using SQL queries to both fetch and create the new rows in the new format table and test which approach is faster. Currently my prisma approach is quite slow, it will take about a 2.5 months to migrate the data at my current pace.\n\nHow can I use the same cuid() function that prisma uses in its schema.prisma on a javascript file?\nMy database uses PostgreSQL.\n\nI've tried calling the cuid() function but it shows up as not installed. I have been doing research on the cuid() packages for npm but I'm not sure if they are the same as the one Prisma uses. I would only use the package to create the ID's of all the migrated data, as any new data would be generated directly with the prisma create function.\n\nI want something similar to this:\n\n```\nquery = `INSERT INTO new_format_table(id, attr1, attr2, attr3)\nVALUES(${cuid()}, val1, val2, val3)`\n```\n\n========================================\n\nCode:\n```js\nquery = `INSERT INTO new_format_table(id, attr1, attr2, attr3)\nVALUES(${cuid()}, val1, val2, val3)`\n```\n\n```text\ncuid()\n```\n\n```bash\nnpm install --save @paralleldrive/cuid2\n```\n\n```js\nimport { createId } from '@paralleldrive/cuid2';\nconst id = createId();\n```\n\n```text\nVARCHAR(30)\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":43,"estimatedTokens":459}}231{"id":"stack-73189707","source":"stackoverflow","questionId":73189707,"title":"how to do Prisma soft delete with NestJS?","tags":["nestjs","prisma"],"text":"Title: how to do Prisma soft delete with NestJS?\nTags: nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI had tried to implement this method in my application. but I don't have depth knowledge of Prisma. Kindly explain that with some examples.\n\n========================================\n\nTop Answer:\nwith depracation of middleware now its done by using extensions, you can check this article I wrote https://medium.com/@erciliomarquesmanhica/implementing-soft-delete-in-prisma-using-client-extensions-a-step-by-step-guide-for-nestjs-51a9d0716831 but here is short version of it:\n\n**Step 1: Setting up Prisma**\n\nI assume you already did this, if not please this docs Prisma on Nestjs.\n\n**Step 2: Adding Soft Delete Field**\n\nNow that we have Prisma configured, we need to add the flag property on our models, this can be a boolean or date, usually people use date to also store when it was deleted. so in this step we will add the property deleted_at.\n\n**Step 3: Implementing Soft Delete Logic**\n\nSo if your did the step one correctly you endup with a PrismaService , so in order to add that soft delete logic to our prisma service we used to use middlwares, but it is depracated now, and we are currently doing it by adding client extensions .\n\nSo lets create those extensions then:\n\nCreate a file to hold your prisma extensions can call it prisma.extensions.ts\n\n```\nimport { Prisma } from '@prisma/client';\n \n //extension for soft delete\n export const softDelete = Prisma.defineExtension({\n name: 'softDelete',\n model: {\n $allModels: {\n async delete(\n this: M,\n where: Prisma.Args['where'],\n ): Promise> {\n const context = Prisma.getExtensionContext(this);\n \n return (context as any).update({\n where,\n data: {\n deleted_at: new Date(),\n },\n });\n },\n },\n },\n });\n \n //extension for soft delete Many\n export const softDeleteMany = Prisma.defineExtension({\n name: 'softDeleteMany',\n model: {\n $allModels: {\n async deleteMany(\n this: M,\n where: Prisma.Args['where'],\n ): Promise> {\n const context = Prisma.getExtensionContext(this);\n \n return (context as any).updateMany({\n where,\n data: {\n deleted_at: new Date(),\n },\n });\n },\n },\n },\n });\n \n //extension for filtering soft deleted rows from queries\n export const filterSoftDeleted = Prisma.defineExtension({\n name: 'filterSoftDeleted',\n query: {\n $allModels: {\n async $allOperations({ model, operation, args, query }) {\n if (\n operation === 'findUnique' ||\n operation === 'findFirst' ||\n operation === 'findMany'\n ) {\n args.where = { ...args.where, deleted_at: null };\n return query(args);\n }\n return query(args);\n },\n },\n },\n });\n```\n\nThese are pretty self explanatory extensions, if you are having problems understanding them I recommend you to go ready the docs client extensions, its pretty straight forward.\n\n**Step 4: Adding the extension to Prisma Service**\n\nSo this step can be a little bit confusing. why you would ask!\n\nFirst by intuition you will be tempeted to just go on PrismaService and add the extensions like this:\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\nimport {\n filterSoftDeleted,\n softDelete,\n softDeleteMany,\n} from './prisma.extension';\n\n@Injectable()\nexport class DatabaseService\n extends PrismaClient \n implements OnModuleInit\n{\n async onModuleInit() {\n await this.$connect();\n this.$extends(softDelete) //adding extensions\n .$extends(softDeleteMany)\n .$extends(filterSoftDeleted);\n }\n}\n```\n\nAnd I dont blame you, I first did it like this, and didnt work, why? because you need to add the extensions explicitly to the client. if its not clear dont worry, you will get it as we go.\n\nSo how do we actually add the extensions to the Prisma Service?\n\nWe will add the extension to PrismaService by extending a CustomPrismaClient of ours, which already has the extensions added. what I mean by that is that we will create a CustomPrismaClient and then extend it on our PrismaService.\n\nSo first lets create the CustomPrismaClient. create a file, can call it custom-prisma-client.ts and add these code:\n\n```\nimport { PrismaClient } from '@prisma/client';\nimport {\n filterSoftDeleted,\n softDelete,\n softDeleteMany,\n} from './prisma.extension';\n\n//function to give us a prismaClient with extensions we want\nexport const customPrismaClient = (prismaClient: PrismaClient) => {\n return prismaClient\n .$extends(softDelete) //here we add our created extensions\n .$extends(softDeleteMany)\n .$extends(filterSoftDeleted);\n};\n\n//Our Custom Prisma Client with the client set to the customPrismaClient with extension\nexport class PrismaClientExtended extends PrismaClient {\n customPrismaClient: CustomPrismaClient;\n\n get client() {\n if (!this.customPrismaClient)\n this.customPrismaClient = customPrismaClient(this);\n\n return this.customPrismaClient;\n }\n}\n\n//Create a type to our funtion\nexport type CustomPrismaClient = ReturnType;\n```\n\nSo I tried to add comments for increase your understanding, but basically we are creating a helper function that given a prismaClient it returns us that prismaClient with our extensions. and then we use that function on our PrismaClientExtended to set extensions.\n\nWIth that done, now all we need to do is extend our PrismaClientExtended class on PrismaService:\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\n\n@Injectable()\nexport class DatabaseService\n extends PrismaClientExtended // we now extending PrismaClientExtended\n implements OnModuleInit\n{\n async onModuleInit() {\n await this.$connect();\n }\n}\n```\n\n**Step 5: How to use it?**\n\nWell, I am adding this step because if you are like me, all my queries where done in some way that would no work with extensions, let me show you:\n\n```\nremove(id: number): Promise {\n return this.prismaService.posts.delete({\n where: {\n id: id,\n },\n });\n}\n```\n\nso this usually works fine, but remember we added our extensions to the client of our prismaService, thats why we need to use the client, and if you look closely the parameters already expects the where object, that why you send the object directy.\n\n```\nremove(id: number): Promise {\n return this.prismaService.client.posts.delete({\n id: id,\n });\n}\n```\n\ncompare these two closely, many people will rush these step and fail.\n\nthe same goes to the deleteMany method:\n\n```\nremoveAllPostsByUserId(id: number): Promise {\n return this.prismaService.client.posts.deleteMany({\n user_id: id,\n });\n}\n```\n\nand for the rest of queries you just need to use client, like this:\n\n```\nfindAll(): Promise {\n return this.prismaService.client.posts.findMany({\n include: { comments: true },\n });\n}\n```\n\n========================================\n\nCode:\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Post {\n  id      Int     @id @default(autoincrement())\n  title   String\n  content String?\n  user    User?   @relation(fields: [userId], references: [id])\n  userId  Int?\n  tags    Tag[]\n  views   Int     @default(0)\n  deleted Boolean @default(false)\n}\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n\nconst prisma = new PrismaClient({})\n\nasync function main() {\n  /***********************************/\n  /* SOFT DELETE MIDDLEWARE */\n  /***********************************/\n\n  prisma.$use(async (params, next) => {\n    // Check incoming query type\n    if (params.model == 'Post') {\n      if (params.action == 'delete') {\n        // Delete queries\n        // Change action to an update\n        params.action = 'update'\n        params.args['data'] = { deleted: true }\n      }\n      if (params.action == 'deleteMany') {\n        // Delete many queries\n        params.action = 'updateMany'\n        if (params.args.data != undefined) {\n          params.args.data['deleted'] = true\n        } else {\n          params.args['data'] = { deleted: true }\n        }\n      }\n    }\n    return next(params)\n  })\n```\n\n```text\nschema.prisma\n```\n\n```text\n{ deleted: true }\n```\n\n```text\nscript.ts\n```\n\n```text\nimport { Prisma } from '@prisma/client';\n    \n    //extension for soft delete\n    export const softDelete = Prisma.defineExtension({\n      name: 'softDelete',\n      model: {\n        $allModels: {\n          async delete<M, A>(\n            this: M,\n            where: Prisma.Args<M, 'delete'>['where'],\n          ): Promise<Prisma.Result<M, A, 'update'>> {\n            const context = Prisma.getExtensionContext(this);\n    \n            return (context as any).update({\n              where,\n              data: {\n                deleted_at: new Date(),\n              },\n            });\n          },\n        },\n      },\n    });\n    \n    //extension for soft delete Many\n    export const softDeleteMany = Prisma.defineExtension({\n      name: 'softDeleteMany',\n      model: {\n        $allModels: {\n          async deleteMany<M, A>(\n            this: M,\n            where: Prisma.Args<M, 'deleteMany'>['where'],\n          ): Promise<Prisma.Result<M, A, 'updateMany'>> {\n            const context = Prisma.getExtensionContext(this);\n    \n            return (context as any).updateMany({\n              where,\n              data: {\n                deleted_at: new Date(),\n              },\n            });\n          },\n        },\n      },\n    });\n    \n    //extension for filtering soft deleted rows from queries\n    export const filterSoftDeleted = Prisma.defineExtension({\n      name: 'filterSoftDeleted',\n      query: {\n        $allModels: {\n          async $allOperations({ model, operation, args, query }) {\n            if (\n              operation === 'findUnique' ||\n              operation === 'findFirst' ||\n              operation === 'findMany'\n            ) {\n              args.where = { ...args.where, deleted_at: null };\n              return query(args);\n            }\n            return query(args);\n          },\n        },\n      },\n    });\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\nimport {\n  filterSoftDeleted,\n  softDelete,\n  softDeleteMany,\n} from './prisma.extension';\n\n@Injectable()\nexport class DatabaseService\n  extends PrismaClient \n  implements OnModuleInit\n{\n  async onModuleInit() {\n    await this.$connect();\n    this.$extends(softDelete) //adding extensions\n      .$extends(softDeleteMany)\n      .$extends(filterSoftDeleted);\n  }\n}\n```\n\n```text\nimport { PrismaClient } from '@prisma/client';\nimport {\n  filterSoftDeleted,\n  softDelete,\n  softDeleteMany,\n} from './prisma.extension';\n\n//function to give us a prismaClient with extensions we want\nexport const customPrismaClient = (prismaClient: PrismaClient) => {\n  return prismaClient\n    .$extends(softDelete) //here we add our created extensions\n    .$extends(softDeleteMany)\n    .$extends(filterSoftDeleted);\n};\n\n//Our Custom Prisma Client with the client set to the customPrismaClient with extension\nexport class PrismaClientExtended extends PrismaClient {\n  customPrismaClient: CustomPrismaClient;\n\n  get client() {\n    if (!this.customPrismaClient)\n      this.customPrismaClient = customPrismaClient(this);\n\n    return this.customPrismaClient;\n  }\n}\n\n//Create a type to our funtion\nexport type CustomPrismaClient = ReturnType<typeof customPrismaClient>;\n```\n\n```text\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClientExtended } from './custom-prisma-client';\n\n@Injectable()\nexport class DatabaseService\n  extends PrismaClientExtended // we now extending PrismaClientExtended\n  implements OnModuleInit\n{\n  async onModuleInit() {\n    await this.$connect();\n  }\n}\n```\n\n```text\nremove(id: number): Promise<any> {\n  return this.prismaService.posts.delete({\n    where: {\n      id: id,\n    },\n  });\n}\n```\n\n```text\nremove(id: number): Promise<any> {\n  return this.prismaService.client.posts.delete({\n      id: id,\n  });\n}\n```\n\n```text\nremoveAllPostsByUserId(id: number): Promise<any> {\n  return this.prismaService.client.posts.deleteMany({\n    user_id: id,\n  });\n}\n```\n\n```text\nfindAll(): Promise<Posts[]> {\n  return this.prismaService.client.posts.findMany({\n    include: { comments: true },\n  });\n}\n```\n\n========================================\n\nComments:\n- What do you mean by `soft delete`? Once data in Prisma is deleted, it's permanently deleted. There is no concept of a soft delete unless you implement it at the database level. Please see the Stack Overflow \"How to Ask\" guide for how to ask a good question - stackoverflow.com/help/how-to-ask\n- @SheaHunterBelsky, it is a good question. In fact, there is documentation for it. Don't judge people too quickly! prisma.io/docs/concepts/components/prisma-client/middleware/&zwnj;&#8203;&hellip;\n- This comment was a year ago - My original comment meant to say that Prisma doesn't have this functionality, and it had to be added. At the time of my original comment, that documentation did not exist!\n- I found this package which handles more things github.com/olivierwilkinson/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":481,"estimatedTokens":3238}}232{"id":"stack-72287494","source":"stackoverflow","questionId":72287494,"title":"Using enums from prisma in nestJS graphQL models","tags":["enums","graphql","nestjs","prisma"],"text":"Title: Using enums from prisma in nestJS graphQL models\nTags: enums, graphql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nMy object that is supposed to be returned:\n\n```\n@ObjectType()\nexport class User {\n @Field(() => String)\n email: string\n\n @Field(() => [Level])\n level: Level[]\n}\n```\n\nLevel is an enum generated by prisma, defined in schema.prisma:\n\n```\nenum Level {\n EASY\n MEDIUM\n HARD\n}\n```\n\nNow I'm trying to return this User object in my GraphQL Mutation:\n\n```\n@Mutation(() => User, { name: 'some-endpoint' })\n```\n\nWhen running this code, I'm getting the following error:\n\n```\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the \"Level\". Make sure your class is decorated with an appropriate decorator.\n```\n\nWhat am I doing wrong here? Can't enums from prisma be used as a field?\n\n========================================\n\nTop Answer:\nYou're probably missing the registration of the enum type in GraphQL:\n\n```\n// user.model.ts\nregisterEnumType(Level, { name: \"Level\" });\n```\n\n========================================\n\nCode:\n```js\n@ObjectType()\nexport class User {\n  @Field(() => String)\n  email: string\n\n  @Field(() => [Level])\n  level: Level[]\n}\n```\n\n```text\nenum Level {\n  EASY\n  MEDIUM\n  HARD\n}\n```\n\n```js\n@Mutation(() => User, { name: 'some-endpoint' })\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the \"Level\". Make sure your class is decorated with an appropriate decorator.\n```\n\n```text\nimport { Level } from '@prisma/client'\n\n@ObjectType()\nexport class User {\n  @Field(() => String)\n  email: string\n\n  @Field(() => Level)\n  level: Level\n}\n\nregisterEnumType(Level, {\n  name: 'Level',\n});\n```\n\n```text\nregisterEnumType\n```\n\n```text\n@Field(() => Enum)\n```\n\n```text\n// user.model.ts\nregisterEnumType(Level, { name: \"Level\" });\n```\n\n```text\nenum Role {\n  USER = 'USER',\n  ADMIN = 'ADMIN',\n}\n\nregisterEnumType(Role, {\n  name: 'Role',\n});\n\nexport class CreateUserInput {\n@IsEnum(Role)\n@Field(() => Role, { nullable: true })\nrole?: Role;\n}\n```\n\n```text\nasync create(createUserInput: CreateUserInput): Promise<User> {\n    return this.prisma.user.create({\n      data: {\n        ...createUserInput,\n      },\n    });\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":138,"estimatedTokens":555}}233{"id":"stack-71926451","source":"stackoverflow","questionId":71926451,"title":"Problem with prisma .upsert, Unkown argument","tags":["javascript","postgresql","prisma"],"text":"Title: Problem with prisma .upsert, Unkown argument\nTags: javascript, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI have problem with prisma upsert(), I get info:\n\nPrismaClientValidationError: Invalid `prisma.prismaUser.upsert()`\ninvocation:\n\n{ where: {\nemail: 'viola@prisma.io'\n~~~~~ }, update: {\nname: 'Viola the Magnificent' }, create: {\nemail: 'viola@prisma.io',\nname: 'Viola the Magnificent',\nprofileViews: 0,\nrole: 'admin' } }\n\nUnknown arg `email` in where.email for type\nprismaUserWhereUniqueInput. Did you mean `id`? Available args: type\nprismaUserWhereUniqueInput { id?\n\nMy code:\nschema.prisma\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel prismaUser {\n id Int @id @default(autoincrement())\n name String @db.VarChar(255)\n email String @db.VarChar(255)\n profileViews Int\n role String @db.VarChar(255)\n}\n```\n\nnode.js\n\n```\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst prisma = new PrismaClient();\n\n// A `main` function so that you can use async/await\nasync function main() {\n await prisma.prismaUser.upsert({\n where: {\n email: \"viola@prisma.io\",\n },\n update: {\n name: \"Viola the Magnificent\",\n },\n create: {\n email: \"viola@prisma.io\",\n name: \"Viola the Magnificent\",\n profileViews: 0,\n role: \"admin\",\n },\n });\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n```\n\nAnyone can help me and explain what is wrong?\n\n========================================\n\nCode:\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel prismaUser {\n  id           Int    @id @default(autoincrement())\n  name         String @db.VarChar(255)\n  email        String @db.VarChar(255)\n  profileViews Int\n  role         String @db.VarChar(255)\n}\n```\n\n```text\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst prisma = new PrismaClient();\n\n// A `main` function so that you can use async/await\nasync function main() {\n  await prisma.prismaUser.upsert({\n    where: {\n      email: \"viola@prisma.io\",\n    },\n    update: {\n      name: \"Viola the Magnificent\",\n    },\n    create: {\n      email: \"viola@prisma.io\",\n      name: \"Viola the Magnificent\",\n      profileViews: 0,\n      role: \"admin\",\n    },\n  });\n}\n\nmain()\n  .catch((e) => {\n    throw e;\n  })\n  .finally(async () => {\n    await prisma.$disconnect();\n  });\n```\n\n```text\nprisma.prismaUser.upsert()\n```\n\n```text\nemail\n```\n\n```text\nid\n```\n\n```text\nmodel prismaUser {\n  id           Int    @id @default(autoincrement())\n  name         String @db.VarChar(255)\n  email        String @unique @db.VarChar(255)\n  profileViews Int\n  role         String @db.VarChar(255)\n}\n```\n\n```text\nupsert\n```\n\n```text\n@unique\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":170,"estimatedTokens":752}}234{"id":"stack-64553202","source":"stackoverflow","questionId":64553202,"title":"Prisma doesn't generate files when running prisma init","tags":["docker","docker-compose","graphql","prisma","prisma-graphql"],"text":"Title: Prisma doesn't generate files when running prisma init\nTags: docker, docker-compose, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nRunning prisma init does not generate files. It not generates the 3 files below.\n\n- datamodel.graphql\n\n- docker-compose.yml\n\n- prisma.yml\n\nend up getting this error:-\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Project not found: 'graphiql@default'\",\n \"code\": 3016,\n \"requestId\": \"local:api:cjh3r908l000s0834adw100sj\"\n }\n ] \n}\n```\n\n========================================\n\nCode:\n```text\n{\n     \"errors\": [\n     {\n        \"message\": \"Project not found: 'graphiql@default'\",\n        \"code\": 3016,\n        \"requestId\": \"local:api:cjh3r908l000s0834adw100sj\"\n     }\n  ] \n}\n```\n\n```text\n$ nvm install 12.19.1\n$ nvm use 12.19.1\n$ node -v                   // Check and confirm your node version\n\n$ prisma init <project_name>\n```\n\n```text\nNode v14.x.x.\n```\n\n```text\n$ prisma init <project_name>\n```\n\n```text\nv12.x.x\n```\n\n```text\nv.12.19.1\n```\n\n```text\nNode v12.19.1\n```\n\n```text\nv14.x.x\n```\n\n```text\nnvm\n```\n\n========================================\n\nComments:\n- Prisma 1 is an older version. As you're getting started, go for Prisma 2 prisma.io/docs/getting-started/quickstart-node","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":82,"estimatedTokens":307}}235{"id":"stack-63571322","source":"stackoverflow","questionId":63571322,"title":"PRISMA: Getting type error on where clause in update method","tags":["orm","prisma"],"text":"Title: PRISMA: Getting type error on where clause in update method\nTags: orm, prisma\nSource: Stack Overflow\n\nQuestion:\nHave a specific Prisma ORM library error that I need help with.\n\nI have created a migration and pushed it to a postgres db.\n\nI have generated the client model for Prisma and am able to findAll and insert data using the create method.\n\nWhere I am having trouble is the update method.\n\nHere's my code\n\n```\napp.post(\"/articles/:title\", async (req: Request, res: Response) => {\n const article = await prisma.article.update({\n where: { title: req.params.title },\n data: { title: req.body.title, content: req.body.content },\n })\n res.send('The article was posted sucessfully.' + article)\n})\n```\n\nI am getting the following error which makes me think that the client is not finding a type 'title' when using the where argument.\n\napp.ts:65:14 - error TS2322: Type '{ title: string; }' is not assignable to type 'ArticleWhereUniqueInput'.\nObject literal may only specify known properties, and 'title' does not exist in type 'ArticleWhereUniqueInput'.\n\n65 where: { title: req.params.title },\n~~~~~~~~~~~~~~~~~~~~~~~\n\nnode_modules/.prisma/client/index.d.ts:784:3\n784 where: ArticleWhereUniqueInput\n~~~~~\nThe expected type comes from property 'where' which is declared here on type 'Subset'\n\nHas anyone else had this issue?\nI tried to introspect the database just to make sure the database was captured exactly as is, with title and content fields and then generated the client again.\n\nMany thanks\nJames\n\n========================================\n\nTop Answer:\nUse `.(find/update/delete)Many()` if you are trying to query with multi values.\n\n========================================\n\nCode:\n```text\napp.post(\"/articles/:title\", async (req: Request, res: Response) => {\n  const article = await prisma.article.update({\n    where: { title: req.params.title },\n    data: { title: req.body.title, content: req.body.content },\n  })\n  res.send('The article was posted sucessfully.' + article)\n})\n```\n\n```text\n.(find/update/delete)Many()\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to upsert new record in Prisma without an ID?","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":70,"estimatedTokens":544}}236{"id":"stack-62457267","source":"stackoverflow","questionId":62457267,"title":"Remove all items in table with Prisma2 and Jest","tags":["node.js","graphql","prisma","prisma-graphql","prisma2"],"text":"Title: Remove all items in table with Prisma2 and Jest\nTags: node.js, graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nI would like to know how can I remove all items in table with Prisma2 and Jest ?\n\nI read the CRUD documentation and I try with this :\n\nuser.test.js\n\n```\n....\nimport { PrismaClient } from \"@prisma/client\"\n\nbeforeEach(async () => {\n const prisma = new PrismaClient()\n await prisma.user.deleteMany({})\n})\n...\n```\n\nBut I have an error :\n\n```\nInvalid `prisma.user.deleteMany()` invocation:\nThe change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.\n```\n\nMy Database\n\n```\nCREATE TABLE User (\n id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n name VARCHAR(255),\n email VARCHAR(255) UNIQUE NOT NULL,\n password VARCHAR(255) NOT NULL\n);\n\nCREATE TABLE Post (\n id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n title VARCHAR(255) NOT NULL,\n createdAt TIMESTAMP NOT NULL DEFAULT now(),\n content TEXT,\n published BOOLEAN NOT NULL DEFAULT false,\n fk_user_id INTEGER NOT NULL,\n CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE\n);\n```\n\nschema.prisma\n\n```\nmodel Post {\n content String?\n createdAt DateTime @default(now())\n fk_user_id Int\n id Int @default(autoincrement()) @id\n published Boolean @default(false)\n title String\n author User @relation(fields: [fk_user_id], references: [id])\n\n @@index([fk_user_id], name: \"fk_user_id\")\n}\n\nmodel User {\n email String @unique\n id Int @default(autoincrement()) @id\n name String?\n password String @default(\"\")\n Post Post[]\n Profile Profile?\n}\n```\n\n========================================\n\nTop Answer:\nAlternative solution:\n\nI found a guide from a medium article. But here's the code I'm using based from that article the only difference is the table names are dynamic.\n\nIt works well if you set cascade deletes on the tables properly. Either way, you can use the one from the article or maybe turn off foreign key checks instead\n\nYou can also create a separate function `truncateTable` and pass a table name or prisma model. Or maybe pass an array of tablenames to `refreshDatabase` instead.\n\n\r\n\r\n\n```\nimport prisma from .....\nimport {Prisma} from \".prisma/client\";\n\nconst tableNames = Object.values(Prisma.ModelName);\n\nexport default async function refreshDatabase() {\n for (const tableName of tableNames) {\n await prisma.$queryRawUnsafe(`TRUNCATE TABLE \"${tableName}\" RESTART IDENTITY CASCADE`)\n }\n}\n```\n\n========================================\n\nCode:\n```text\n....\nimport { PrismaClient } from \"@prisma/client\"\n\nbeforeEach(async () => {\n    const prisma = new PrismaClient()\n    await prisma.user.deleteMany({})\n})\n...\n```\n\n```text\nInvalid `prisma.user.deleteMany()` invocation:\nThe change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.\n```\n\n```text\nCREATE TABLE User (\n  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n  name VARCHAR(255),\n  email VARCHAR(255) UNIQUE NOT NULL,\n  password VARCHAR(255) NOT NULL\n);\n\nCREATE TABLE Post (\n  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n  title VARCHAR(255) NOT NULL,\n  createdAt TIMESTAMP NOT NULL DEFAULT now(),\n  content TEXT,\n  published BOOLEAN NOT NULL DEFAULT false,\n  fk_user_id INTEGER NOT NULL,\n  CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE\n);\n```\n\n```text\nmodel Post {\n  content    String?\n  createdAt  DateTime @default(now())\n  fk_user_id Int\n  id         Int      @default(autoincrement()) @id\n  published  Boolean  @default(false)\n  title      String\n  author     User     @relation(fields: [fk_user_id], references: [id])\n\n  @@index([fk_user_id], name: \"fk_user_id\")\n}\n\nmodel User {\n  email    String   @unique\n  id       Int      @default(autoincrement()) @id\n  name     String?\n  password String   @default(\"\")\n  Post     Post[]\n  Profile  Profile?\n}\n```\n\n```text\nbeforeEach(async () => {\n    const prisma = new PrismaClient()\n    await prisma.post.deleteMany({where: {...}}) //delete posts first\n    await prisma.user.deleteMany({})\n})\n```\n\n```text\nPost\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nPosts\n```\n\n```text\nprisma.$executeRaw(`TRUNCATE TABLE \"${table}\" RESTART IDENTITY CASCADE;`)\n```\n\n```js\nimport prisma from .....\nimport {Prisma} from \".prisma/client\";\n\nconst tableNames = Object.values(Prisma.ModelName);\n\nexport default async function refreshDatabase() {\n  for (const tableName of tableNames) {\n    await prisma.$queryRawUnsafe(`TRUNCATE TABLE \"${tableName}\" RESTART IDENTITY CASCADE`)\n  }\n}\n```\n\n```text\ntruncateTable\n```\n\n```text\nrefreshDatabase\n```\n\n========================================\n\nComments:\n- Thank you for your answer ! It's a bug with Prisma 2 github.com/prisma/prisma/issues/2810","metadata":{"transformedAt":"2026-08-18T18:33:14.840Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":216,"estimatedTokens":1191}}237{"id":"stack-71195586","source":"stackoverflow","questionId":71195586,"title":"creating objects for 1:n relation with prisma","tags":["typescript","orm","prisma"],"text":"Title: creating objects for 1:n relation with prisma\nTags: typescript, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nI have two models, Fish and BoardFish\nwith a 1:1 relation - BoardFish is a type of Fish\nI created some seed Fish with named types.\n\nhow can I do this in Prisma? I think i have the schema setup, but inserting data isn't really documented apart from fancy/nested types.\n\nschema:\n\n```\nmodel Fish {\n name String @id\n boardFish BoardFish[]\n}\n\nmodel BoardFish {\n id Int @id @default(autoincrement())\n name String\n fishType Fish @relation(fields: [name], references: [name])\n}\n```\n\ntry to create:\n\n```\nlet fishes = []\n for (let c = 0; c but I'm unable to do the insertion:\n\n```\n→ 35 const fish = await prisma.boardFish.create({\n data: {\n fishType: 'salmon',\n ~~~~~~~~\n px: 3,\n py: 5\n }\n })\n\nArgument fishType: Got invalid value 'salmon' on prisma.createOneBoardFish. Provided String, expected FishCreateNestedOneWithoutBoardFishInput:\ntype FishCreateNestedOneWithoutBoardFishInput {\n create?: FishCreateWithoutBoardFishInput | FishUncheckedCreateWithoutBoardFishInput\n connectOrCreate?: FishCreateOrConnectWithoutBoardFishInput\n connect?: FishWhereUniqueInput\n}\n```\n\nThe types involved are pretty hard to , Prisma seems to really take the cake for most \"magic\" with thousands of lines of auto generated code, which I've been digging through without much luck.\n\n========================================\n\nCode:\n```text\nmodel Fish {\n    name      String      @id\n    boardFish BoardFish[]\n}\n\nmodel BoardFish {\n    id       Int    @id @default(autoincrement())\n    name     String\n    fishType Fish   @relation(fields: [name], references: [name])\n}\n```\n\n```text\nlet fishes = []\n        for (let c = 0; c < fishCount; c++) {\n            const fishType = await prisma.fish.findFirst({ where: { name: 'salmon' } })\n            const fishData = {\n                fishType: fishType!.name,\n                // name: 'salmon',\n                px: 0,\n                py: 0,\n            }\n            const fish = await prisma.boardFish.create({ data: fishData })\n            fishes.push(fish)\n        }\n```\n\n```text\n→ 35 const fish = await prisma.boardFish.create({\n       data: {\n         fishType: 'salmon',\n                   ~~~~~~~~\n         px: 3,\n         py: 5\n       }\n     })\n\nArgument fishType: Got invalid value 'salmon' on prisma.createOneBoardFish. Provided String, expected FishCreateNestedOneWithoutBoardFishInput:\ntype FishCreateNestedOneWithoutBoardFishInput {\n  create?: FishCreateWithoutBoardFishInput | FishUncheckedCreateWithoutBoardFishInput\n  connectOrCreate?: FishCreateOrConnectWithoutBoardFishInput\n  connect?: FishWhereUniqueInput\n}\n```\n\n```text\nmodel Fish {\n    name      String      @id\n    boardFish BoardFish? // removed autogenerated `[]` and made optional\n}\n\nmodel BoardFish {\n    id       Int    @id @default(autoincrement())\n    name     String\n    fishType Fish   @relation(fields: [name], references: [name])\n}\n```\n\n```js\nconst fish = await prisma.boardFish.create({\n  data: {\n    fishType: {\n      connect: { name: 'salmon' }, // or `connectOrCreate` if it doesn't exist\n    },\n  }\n})\n```\n\n========================================\n\nComments:\n- two things; first: if you want 1:1 relationships, edit your prisma schema to remove the square braces on `boardFish BoardFish[]`, second: to create a related record use prisma's connect api. It looks like you are just doing it with a string `'salmon'`\n- yep thanks, i missed docs on `connect` but makes sense!\n- hey this worked thanks! I missed the `connect` docs","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":130,"estimatedTokens":886}}238{"id":"stack-71259682","source":"stackoverflow","questionId":71259682,"title":"Prisma is opening too many connections with PostgrsQL when running Jest end to end testing","tags":["jestjs","nestjs","prisma"],"text":"Title: Prisma is opening too many connections with PostgrsQL when running Jest end to end testing\nTags: jestjs, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying here to do end to end testing with Jest on a NestJS/GraphQL app and Prisma as my ORM.\n\nWhat happens here is Prisma is opening too many connections with Postgres, I've tried to fix this problem by using prisma.$disconnect() after each test but it doesn't seem to work...\n\nThis is what I've tried so far.\n\n```\nimport { PrismaService } from '../src/prisma.service';\n\ndescribe('Users', () => {\n let app: INestApplication;\n const gql = '/graphql';\n let prisma;\n\n beforeEach(async () => {\n prisma = new PrismaService();\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterEach(async () => {\n await prisma.$disconnect();\n });\n\n it('Query - Users', async () => {\n //Using prisma to query database\n });\n});\n```\n\nMy Prisma service (I got it from NestJS documentation Text ):\n\n```\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n async onModuleInit() {\n await this.$connect();\n }\n\n async enableShutdownHooks(app: INestApplication) {\n this.$on('beforeExit', async () => {\n await app.close();\n });\n }\n}\n```\n\nThese are the errors I'm getting after running all the tests (serially):\n\nhttps://i.sstatic.net/nloMQ.png\n\nI've already looked through Prisma documentation but didn't find anything about how to setup properly a Jest environment with NestJS and Prisma.\n\nThanks for your help !\n\n========================================\n\nTop Answer:\nAfter trying the solution of limiting the number of connections, I start getting timeout in my tests. Searching more, the real problem may be related to a problem that happen only in development, caused to how module reloads are handled by Nest (https://github.com/prisma/prisma/issues/5007#issuecomment-618433162). What solved for me was this\n\n```\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n private prisma: PrismaClient;\n\n constructor() {\n super();\n if (process.env.NODE_ENV === 'production') {\n this.prisma = new PrismaClient();\n } else {\n if (!global.prisma) {\n global.prisma = new PrismaClient();\n }\n this.prisma = global.prisma as PrismaClient;\n }\n }\n\n async onModuleInit() {\n await this.prisma.$connect();\n }\n\n async onModuleDestroy() {\n await this.prisma.$disconnect();\n }\n}\n```\n\nNow your application in development has only one instance of client, what avoid the bug related to Nest\n\n========================================\n\nCode:\n```text\nimport { PrismaService } from '../src/prisma.service';\n\ndescribe('Users', () => {\n  let app: INestApplication;\n  const gql = '/graphql';\n  let prisma;\n\n  beforeEach(async () => {\n    prisma = new PrismaService();\n\n    const moduleFixture: TestingModule = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n\n    app = moduleFixture.createNestApplication();\n    await app.init();\n  });\n\n  afterEach(async () => {\n    await prisma.$disconnect();\n  });\n\n  it('Query - Users', async () => {\n    //Using prisma to query database\n  });\n});\n```\n\n```text\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });\n  }\n}\n```\n\n```text\npostgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public&connection_limit=1\n```\n\n```text\nconnection_limit=1\n```\n\n```text\nexport class PrismaService extends PrismaClient implements OnModuleInit {\n  private prisma: PrismaClient;\n\n  constructor() {\n    super();\n    if (process.env.NODE_ENV === 'production') {\n      this.prisma = new PrismaClient();\n    } else {\n      if (!global.prisma) {\n        global.prisma = new PrismaClient();\n      }\n      this.prisma = global.prisma as PrismaClient;\n    }\n  }\n\n  async onModuleInit() {\n    await this.prisma.$connect();\n  }\n\n  async onModuleDestroy() {\n    await this.prisma.$disconnect();\n  }\n}\n```\n\n========================================\n\nComments:\n- Looks like it did the trick. Thanks for your help !\n- This limits the connection to the database, but connections are not closing after the request completes or times out.","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":190,"estimatedTokens":1160}}239{"id":"stack-54047369","source":"stackoverflow","questionId":54047369,"title":"Prisma API returns relation but client returns \"cannot return null for non-nullable field..\"","tags":["javascript","graphql","prisma"],"text":"Title: Prisma API returns relation but client returns \"cannot return null for non-nullable field..\"\nTags: javascript, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nWhen I try to return fields from a one-to-many relation in Prisma client playground it returns the following error:\n\n Cannot return null for non-nullable field DeviceConfig.device.\n\nWhat in my resolver or client could be causing this?\n\nWhen running the following query on the backend Prisma API playground it does return the correct data so that tells me my mutations and relationship is good.\n\n**Datamodel**\n\n```\ntype Device {\n ...\n model: String! @unique\n ...\n configs: [DeviceConfig] @relation(name: \"DeviceConfigs\", onDelete: CASCADE)\n}\n\ntype DeviceConfig {\n id: ID! @unique\n device: Device! @relation(name: \"DeviceConfigs\", onDelete: SET_NULL)\n name: String!\n ...\n}\n```\n\n**Resolver**\n\n```\ndeviceConfig: async (parent, { id }, context, info) => context.prisma.deviceConfig({ id }, info)\n```\n\n**Query**\n\n```\n{\n deviceConfig(id:\"cjqigyian00ef0d206tg116k5\"){\n name\n id\n device{\n model\n }\n }\n}\n```\n\n**Result**\n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field DeviceConfig.device.\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 5\n }\n ],\n \"path\": [\n \"deviceConfig\",\n \"device\"\n ]\n }\n ]\n}\n```\n\nI expect the query to return the model of the device like the backend Prisma API server does\n**Query**\n\n```\n{\n deviceConfig(where:{id:\"cjqigyian00ef0d206tg116k5\"}){\n name\n id\n device{\n id\n model\n }\n }\n}\n```\n\n**Result**\n\n```\n{\n \"data\": {\n \"deviceConfig\": {\n \"name\": \"Standard\",\n \"id\": \"cjqigyian00ef0d206tg116k5\",\n \"device\": {\n \"id\": \"cjqigxzs600e60d20sdw38x7p\",\n \"model\": \"7530\"\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nI think you are mixing Prisma Bindings syntax with Prisma Client syntax. \n\nThe `info` object is something you pass to the bindings to return what the user is asking for. However, this feature is not available in the Prisma Client, which you seem to be using. If you need that feature then you could try Prisma Bindings. \n\nOtherwise, modify your code to something like `context.prisma.deviceConfig({ id }).device()`. I think it can also accept a fragment `context.prisma.deviceConfig({ id }).$fragment('fragment configWithDevice on DeviceConfig { id name device { id model } }')`.\n\n========================================\n\nCode:\n```text\ntype Device {\n  ...\n  model: String! @unique\n  ...\n  configs: [DeviceConfig] @relation(name: \"DeviceConfigs\", onDelete: CASCADE)\n}\n\ntype DeviceConfig {\n  id: ID! @unique\n  device: Device! @relation(name: \"DeviceConfigs\", onDelete: SET_NULL)\n  name: String!\n  ...\n}\n```\n\n```text\ndeviceConfig: async (parent, { id }, context, info) => context.prisma.deviceConfig({ id }, info)\n```\n\n```text\n{\n  deviceConfig(id:\"cjqigyian00ef0d206tg116k5\"){\n    name\n    id\n    device{\n      model\n    }\n  }\n}\n```\n\n```text\n{\n  \"data\": null,\n  \"errors\": [\n    {\n      \"message\": \"Cannot return null for non-nullable field DeviceConfig.device.\",\n      \"locations\": [\n        {\n          \"line\": 5,\n          \"column\": 5\n        }\n      ],\n      \"path\": [\n        \"deviceConfig\",\n        \"device\"\n      ]\n    }\n  ]\n}\n```\n\n```text\n{\n  deviceConfig(where:{id:\"cjqigyian00ef0d206tg116k5\"}){\n    name\n    id\n    device{\n      id\n      model\n    }\n  }\n}\n```\n\n```text\n{\n  \"data\": {\n    \"deviceConfig\": {\n      \"name\": \"Standard\",\n      \"id\": \"cjqigyian00ef0d206tg116k5\",\n      \"device\": {\n        \"id\": \"cjqigxzs600e60d20sdw38x7p\",\n        \"model\": \"7530\"\n      }\n    }\n  }\n}\n```\n\n```text\nconst resolvers = {\n  // Relationship resolvers\n  Device: {\n    configs: (parent, args, context) => context.prisma.device({ id: parent.id }).configs(),\n  },\n  DeviceConfig: {\n    device: (parent, args, context) => context.prisma.deviceConfig({ id: parent.id }).device(),\n  },\n  Query: {\n    ...User.Query,\n    ...Device.Query,\n    ...DeviceConfig.Query,\n  },\n  Mutation: {\n    ...User.Mutation,\n    ...Device.Mutation,\n    ...DeviceConfig.Mutation,\n  },\n};\n```\n\n```text\ninfo\n```\n\n```text\ncontext.prisma.deviceConfig({ id }).device()\n```\n\n```text\ncontext.prisma.deviceConfig({ id }).$fragment('fragment configWithDevice on DeviceConfig { id name device { id model } }')\n```\n\n========================================\n\nComments:\n- Your correct I am migrating from Prisma binding and missed that detail. I tried `context.prisma.deviceConfig({ id }).device()` and got back the following error `Cannot return null for non-nullable field DeviceConfig.name.`. It would be nice to get this to work so I don't have to use the fragment solution. But the fragment worked! Is there a way to request all the fields without having to populate the fragment with all the fields?\n- Looks like the first syntax only returns \"device by deviceConfig\" (like posts by user), but not the device config itself. Perhaps the fragment syntax is the only possibility :/\n- That makes sense, Thank you for the help.","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":240,"estimatedTokens":1233}}240{"id":"stack-69763714","source":"stackoverflow","questionId":69763714,"title":"Does NextJS include libraries that are referenced only in getServerSideProps in the bundle?","tags":["javascript","next.js","prisma"],"text":"Title: Does NextJS include libraries that are referenced only in getServerSideProps in the bundle?\nTags: javascript, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a Next.js page that is fetching data from a database (using prisma as the ORM) inside of `getServerSideProps()`.\n\nI working based on this example from an official Prisma github. Here is a simplified version of the page setup:\n\n```\nimport prisma from 'prisma';\n\nexport const getServerSideProps = async ({ req, res }) => {\n const drafts = await prisma.post.findMany(...);\n};\n\nconst MyPage = () => {return Hello};\nexport default MyPage;\n```\n\nPrisma is imported into the page file and is referenced in `getServerSideProps()` but is not referenced in the actual page component that is exported. My question is, will prisma be included in the bundle sent to the browser with this page? Or is Next smart enough to trim packages that are referenced only in server-side functions?\n\n========================================\n\nCode:\n```text\nimport prisma from 'prisma';\n\nexport const getServerSideProps = async ({ req, res }) => {\n  const drafts = await prisma.post.findMany(...);\n};\n\nconst MyPage = () => {return <div>Hello</div>};\nexport default MyPage;\n```\n\n```text\ngetServerSideProps()\n```\n\n```text\ngetServerSideProps()\n```\n\n========================================\n\nComments:\n- This tool can help you see what is being included in the client bundle: next-code-elimination.vercel.app","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":48,"estimatedTokens":363}}241{"id":"stack-72991027","source":"stackoverflow","questionId":72991027,"title":"Vercel: \"Linting and checking validity of types\" fails on deploy but passes locally","tags":["typescript","next.js","prisma","vercel"],"text":"Title: Vercel: \"Linting and checking validity of types\" fails on deploy but passes locally\nTags: typescript, next.js, prisma, vercel\nSource: Stack Overflow\n\nQuestion:\nWhen running locally, I can run \"next build\" without problems. The command \"vercel build\" also works without problems. But as soon as I deploy to vercel, the \"Linting and checking validity of types\" fails when it's being built on vercel. Typescript is set to strict mode, but it is as if it's even stricter in when running in vercel even though it's the same codebase.\n\nThe app is based on the create-t3 app. It stops building on vercel as soon as I add a \"select\" statement in a prisma findUnique query. Such as in the \"check-credentials\" file.\n\nIn the console in vercel, it would output the following error:\n\n```\ninfo - Linting and checking validity of types...\nFailed to compile.\n./src/pages/api/user/check-credentials.ts:33:7\nType error: Type '{ id: true; name: true; email: true; image: true; password: true; }' is not assignable to type 'UserSelect'.\n Object literal may only specify known properties, and 'password' does not exist in type 'UserSelect'.\n 31 | email: true,\n 32 | image: true,\n> 33 | password: true,\n | ^\n 34 | },\n 35 | });\n 36 | if (user && user.password == hashPassword(req.body.password)) {\n```\n\nI have created a clone of the repository, as my best guess is that there might be a problem with ts validation and linting being ignored locally, but not on deploys:\nhttps://github.com/Andreaswt/t3-app\n\n========================================\n\nCode:\n```text\ninfo  - Linting and checking validity of types...\nFailed to compile.\n./src/pages/api/user/check-credentials.ts:33:7\nType error: Type '{ id: true; name: true; email: true; image: true; password: true; }' is not assignable to type 'UserSelect'.\n  Object literal may only specify known properties, and 'password' does not exist in type 'UserSelect'.\n  31 |       email: true,\n  32 |       image: true,\n> 33 |       password: true,\n     |       ^\n  34 |     },\n  35 |   });\n  36 |   if (user && user.password == hashPassword(req.body.password)) {\n```\n\n```text\ndb-generate-client\n```\n\n========================================\n\nComments:\n- This was it. I added \"postinstall\": \"prisma generate\" to my package.json and redeployed in vercel, which generated the prisma client in vercel as it should. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":587}}242{"id":"stack-71791433","source":"stackoverflow","questionId":71791433,"title":"Prisma NOT equal to true, filtering incorrectly","tags":["postgresql","null","prisma"],"text":"Title: Prisma NOT equal to true, filtering incorrectly\nTags: postgresql, null, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm running a prisma postgres filter query, as below. However when I add the NOT equal to filter, it ends up filtering everything and returning no results, without an error. What am I doing wrong? I have a variety of entries with both is_soundtrack false, true and null. So I should be getting some results. I also commented out another approach to using `NOT`, however this also doesn't work?\n\nI'm wanting to show all results, where is_soundtrack does not equal true.\n\n```\nconst songs = await this.db.song.findMany({\n where: {\n name: {\n contains: \"test string,\n },\n // is_soundtrack: {\n // not: true,\n // },\n NOT: {\n is_soundtrack: true,\n },\n },\n orderBy: {\n spotifyImg640: 'desc',\n }\n})\n```\n\n========================================\n\nTop Answer:\nPrisma converts `isNot: true` to `where column <> true` which does not work.\n\nThis is what I had to do:\n\n```\nawait prisma.questions.findMany({\n where: { OR: [{ keepHidden: false }, { keepHidden: null }] }\n})\n```\n\n========================================\n\nCode:\n```text\nconst songs = await this.db.song.findMany({\n  where: {\n    name: {\n      contains: \"test string,\n    },\n    // is_soundtrack: {\n    //   not: true,\n    // },\n    NOT: {\n      is_soundtrack: true,\n    },\n  },\n  orderBy: {\n    spotifyImg640: 'desc',\n  }\n})\n```\n\n```text\nNOT\n```\n\n```text\nis_soundtrack IS NOT TRUE\n```\n\n```text\nis_soundtrack IS DISTINCT FROM true\n```\n\n```text\n(is_soundtrack = false OR is_soundtrack IS NULL)\n```\n\n```text\nNOT is_soundtrack = true\n```\n\n```text\nawait prisma.questions.findMany({\n    where: { OR: [{ keepHidden: false }, { keepHidden: null }] }\n})\n```\n\n```text\nisNot: true\n```\n\n```text\nwhere column <> true\n```\n\n========================================\n\nComments:\n- the `isNot: true` filter might be useful prisma.io/docs/reference/api-reference/&hellip;\n- See: github.com/prisma/prisma/issues/22262\n- Answer is not prisma query, but postgresql\n- Why was this downvoted ? This is actually the solution to the question and an existing issue in prisma: github.com/prisma/prisma/issues/22262","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":104,"estimatedTokens":538}}243{"id":"stack-76778166","source":"stackoverflow","questionId":76778166,"title":"Prisma findMany where relationship is not null","tags":["javascript","node.js","nestjs","prisma"],"text":"Title: Prisma findMany where relationship is not null\nTags: javascript, node.js, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI have these two low-end models and I want to list all their subcategories with their menus, provided that the menu is not empty.\n\n```\nmodel SubCategory {\n id Int @id @default(autoincrement())\n label String\n image String\n categories Category[] @relation(\"CategoryToSubCategory\")\n menu Menu[] @relation(\"MenuToSubCategory\")\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Menu {\n id Int @id @default(autoincrement())\n name String @db.VarChar(64)\n description String @db.Text\n favoriteMenus FavoriteMenus[]\n ingredients Ingredients[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([chefStoreId], map: \"Menu_chefStoreId_fkey\")\n @@fulltext([name, description])\n}\n```\n\nThe query I am writing is as follows:\n\n```\nconst topCategories = await this.prisma.subCategory.findMany({\n include: {\n menu: {\n where: {\n id: { not: null },\n },\n },\n },\n orderBy: {\n id: 'desc',\n },\n take: 50,\n});\n```\n\nBut it gives me the error `\"Argument`not`must not be null.\"`\n\n========================================\n\nCode:\n```text\nmodel SubCategory {\n  id         Int        @id @default(autoincrement())\n  label      String\n  image      String\n  categories Category[] @relation(\"CategoryToSubCategory\")\n  menu       Menu[]     @relation(\"MenuToSubCategory\")\n  createdAt  DateTime   @default(now())\n  updatedAt  DateTime   @updatedAt\n}\n\nmodel Menu {\n  id                     Int                     @id @default(autoincrement())\n  name                   String                  @db.VarChar(64)\n  description            String                  @db.Text\n  favoriteMenus          FavoriteMenus[]\n  ingredients            Ingredients[]\n  createdAt              DateTime                @default(now())\n  updatedAt              DateTime                @updatedAt\n\n  @@index([chefStoreId], map: \"Menu_chefStoreId_fkey\")\n  @@fulltext([name, description])\n}\n```\n\n```js\nconst topCategories = await this.prisma.subCategory.findMany({\n  include: {\n    menu: {\n      where: {\n        id: { not: null },\n      },\n    },\n  },\n  orderBy: {\n    id: 'desc',\n  },\n  take: 50,\n});\n```\n\n```text\n\"Argument\n```\n\n```text\nmust not be null.\"\n```\n\n```text\nconst topCategories = this.prisma.subCategory.findMany({\n    where: {\n      menu: {\n        some: {},\n      },\n    },\n    include: {\n      menu: true,\n    },\n    orderBy: {\n      id: 'desc',\n    },\n    take: 50,\n  });\n```\n\n```text\nmenu\n```\n\n```text\nMenu\n```\n\n```text\nsubCategory\n```\n\n```text\nsome\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":136,"estimatedTokens":647}}244{"id":"stack-64427407","source":"stackoverflow","questionId":64427407,"title":"Map over collection to upsert into the database. How to batch upsert?","tags":["javascript","database","insert-update","prisma","prisma2"],"text":"Title: Map over collection to upsert into the database. How to batch upsert?\nTags: javascript, database, insert-update, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nSay, I have a data structure coming in from the frontend as follows:\n\n```\nconst userData = [\n {\n id: 11223,\n bb: [\n {\n id: 12,\n },\n {\n id: 34,\n bbb: \"bbb\",\n },\n ],\n },\n {\n id:4234,\n ...\n },\n];\n```\n\nBecause, none/ some/ all of the data may already be in the database, here is what I have come up with:\n\n```\nconst collection = [];\nfor (let i = 0; i To summarise, I am mapping over the userData & `upsert` each object one by one. Within the loop, I map over the child collections & `upsert` them in the db.\n\nMy concern is that I am making a lot of entries into the Db this way. Is this the best way to do this?\n\nAside:\nI previously, tried to do multiple `inserts` within the `upsert`, however, I got stuck with the `update` section as to my knowledge, we cannot upsert multiple records within the `update` nested within `upsert`. Is this correct?\n\n**UPDATE:**\n\nAs requested by Ryan, here is what the Schema looks like:\n\n```\nmodel Cur {\n id Int,\n subCur SubCur[]\n ...\n}\n\nmodel SubCur {\n id Int,\n cur Cur @relation(fields: [curId], references : [id])\n curId Int\n ...\n}\n```\n\nTo summarise, there are many models like 'SubCur' with 1-n relation with 'Cur' model. As the 'UserData' payload, may have some data that is new, some that is update for existing data already in Db, I was curious, whats the best approach to `upsert` the data into the db. To be specific, do I have to insert each one, one at a time?\n\n========================================\n\nCode:\n```text\nconst userData = [\n  {\n    id: 11223,\n    bb: [\n      {\n        id: 12,\n      },\n      {\n        id: 34,\n        bbb: \"bbb\",\n      },\n    ],\n  },\n  {\n    id:4234,\n    ...\n  },\n];\n```\n\n```text\nconst collection = [];\nfor (let i = 0; i < userData.length; i++) {\n  const cur = userData[i];\n  const subCur = cur.bb;\n  const updatedCur = await db.cur.upsert({\n      where: {\n        id : cur.id\n      },\n      update: {\n        ...\n      },\n      create: {\n        ...\n      },\n    })\n  );\n  collection.push(updatedCur);\n  for (let j = 0; j < subCur.length; j++) {\n    const latest = subCur[j];\n    await db.subcur.upsert({\n      where: {\n        id : latest.id\n      },\n      update: {\n        ...\n      },\n      create: {\n        ...\n      },\n    });\n  }\n}\n```\n\n```text\nmodel Cur {\n  id      Int,\n  subCur  SubCur[]\n  ...\n}\n\nmodel SubCur {\n  id      Int,\n  cur     Cur  @relation(fields: [curId], references : [id])\n  curId   Int\n  ...\n}\n```\n\n```text\nupsert\n```\n\n```text\nupsert\n```\n\n```text\ninserts\n```\n\n```text\nupsert\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n```text\nupsert\n```\n\n```text\nupsert\n```\n\n```text\nmodel Cur {\n  id Int @id\n}\n\nmodel Subcur {\n  id  Int     @id\n  bbb String?\n}\n```\n\n```text\nconst collection = await prisma.$transaction(\n    userData.map(cur =>\n      prisma.cur.upsert({\n        where: { id: cur.id },\n        update: {},\n        create: { id: cur.id },\n      })\n    )\n  )\n\n  await prisma.$transaction(\n    userData\n      .flatMap(cur => cur.bb)\n      .map(latest =>\n        prisma.subcur.upsert({\n          where: {\n            id: latest.id,\n          },\n          update: {\n            bbb: latest.bbb,\n          },\n          create: {\n            id: latest.id,\n            bbb: latest.bbb,\n          },\n        })\n      )\n  )\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":207,"estimatedTokens":847}}245{"id":"stack-69319651","source":"stackoverflow","questionId":69319651,"title":"How to reduce Prisma select(or include) field code line","tags":["mysql","express","prisma"],"text":"Title: How to reduce Prisma select(or include) field code line\nTags: mysql, express, prisma\nSource: Stack Overflow\n\nQuestion:\nI am developing with prisma + express + javascript + mysql\n\nprisma version is 2.28,\n\nI have a problem while using prisma.\n\nwhen the model is\n\n```\nmodel User{\n id Int @id @default(autoincrement())\n email String @unique @db.VarChar(30)\n password String? @db.VarChar(200)\n nickname String? @unique @db.VarChar(30)\n profile Profile?\n\n}\nmodel Profile {\n id Int @id @default(autoincrement())\n department String? @db.VarChar(50)\n introduce String? @db.Text\n createdAt DateTime\n updatedAt DateTime?\n user User @relation(fields: [userId], references: [id])\n userId Int\n wellTalent WellTalent[]\n interestTalent InterestTalent[]\n profileImage Image?\n\n @@map(name: \"profiles\")\n}\nmodel InterestTalent {\n id Int @id @default(autoincrement())\n contents String?\n createdAt DateTime\n updatedAt DateTime?\n profile Profile @relation(fields: [profileId], references: [id])\n profileId Int\n\n @@map(name: \"interest_talents\")\n}\n\nmodel WellTalent {\n id Int @id @default(autoincrement())\n contents String?\n createdAt DateTime\n updatedAt DateTime?\n profile Profile @relation(fields: [profileId], references: [id])\n profileId Int\n\n @@map(name: \"well_talents\")\n}\n\nmodel Image {\n id Int @id @default(autoincrement())\n src String? @db.VarChar(200)\n createdAt DateTime\n updatedAt DateTime?\n profile Profile? @relation(fields: [profileId], references: [id])\n profileId Int?\n\n @@map(name: \"images\")\n}\n```\n\nif i want to find the profile data along with user table\n\n```\nconst prisma = new PrismaClient();\n\nconst findByIdWithProfile = async (id) => {\n try {\n return await prisma.user.findUnique({\n where: { id },\n select: {\n id: true,\n nickname: true,\n email: true,\n profile: {\n select: {\n id: true,\n department: true,\n introduce: true,\n wellTalent: {\n select: {\n contents: true,\n },\n },\n interestTalent: {\n select: {\n contents: true,\n },\n },\n profileImage: {\n select: {\n src: true,\n },\n },\n },\n },\n },\n });\n } catch (err) {\n console.error(err);\n }\n};\n```\n\ncode line is very increase..\ni can find User table and Profile table separately, but nest query use to minimize DB access.\n\nbigger the project, the worse it got.\n\nIt seems that the DB structure is structured incorrectly, but the cost is already too high to replace, and I do not know which way is the best.\n\nThanks for your help\n\n========================================\n\nCode:\n```text\nmodel User{\n  id              Int           @id @default(autoincrement())\n  email           String        @unique @db.VarChar(30)\n  password        String?       @db.VarChar(200)\n  nickname        String?       @unique @db.VarChar(30)\n  profile         Profile?\n\n}\nmodel Profile {\n  id             Int              @id @default(autoincrement())\n  department     String?          @db.VarChar(50)\n  introduce      String?          @db.Text\n  createdAt      DateTime\n  updatedAt      DateTime?\n  user           User             @relation(fields: [userId], references: [id])\n  userId         Int\n  wellTalent     WellTalent[]\n  interestTalent InterestTalent[]\n  profileImage   Image?\n\n  @@map(name: \"profiles\")\n}\nmodel InterestTalent {\n  id        Int       @id @default(autoincrement())\n  contents  String?\n  createdAt DateTime\n  updatedAt DateTime?\n  profile   Profile   @relation(fields: [profileId], references: [id])\n  profileId Int\n\n  @@map(name: \"interest_talents\")\n}\n\nmodel WellTalent {\n  id        Int       @id @default(autoincrement())\n  contents  String?\n  createdAt DateTime\n  updatedAt DateTime?\n  profile   Profile   @relation(fields: [profileId], references: [id])\n  profileId Int\n\n  @@map(name: \"well_talents\")\n}\n\nmodel Image {\n  id        Int       @id @default(autoincrement())\n  src       String?   @db.VarChar(200)\n  createdAt DateTime\n  updatedAt DateTime?\n  profile   Profile?  @relation(fields: [profileId], references: [id])\n  profileId Int?\n\n  @@map(name: \"images\")\n}\n```\n\n```js\nconst prisma = new PrismaClient();\n\nconst findByIdWithProfile = async (id) => {\n    try {\n        return await prisma.user.findUnique({\n            where: { id },\n            select: {\n                id: true,\n                nickname: true,\n                email: true,\n                profile: {\n                    select: {\n                        id: true,\n                        department: true,\n                        introduce: true,\n                        wellTalent: {\n                            select: {\n                                contents: true,\n                            },\n                        },\n                        interestTalent: {\n                            select: {\n                                contents: true,\n                            },\n                        },\n                        profileImage: {\n                            select: {\n                                src: true,\n                            },\n                        },\n                    },\n                },\n            },\n        });\n    } catch (err) {\n        console.error(err);\n    }\n};\n```\n\n```js\nconst findByIdWithProfile = async (id) => {\n    try {\n        let data = await prisma.user.findUnique({\n            where: { id },\n            include: {\n                profile: {\n                    include: {\n                        wellTalent: true,\n                        interestTalent: true,\n                        profileImage: true,\n                    },\n                },\n            },\n        });\n        delete data[\"password\"]; // sensitive information we don't want to expose. \n        return data; \n    } catch (err) {\n        console.error(err);\n    }\n};\n```\n\n```text\ninclude\n```\n\n```text\ninclude\n```\n\n```text\nselect\n```\n\n```text\npassword\n```\n\n```text\ndelete\n```\n\n========================================\n\nComments:\n- Hi, could you clarify if returning the very specific selection of fields is a requirement? If it's not necessary, then you could just return all the fields of a certain relation using `include` instead of `select`. If this is an important requirement, then I'm afraid you will have to specify the fields manually like you're doing now. The best you could do is make the code less verbose and easier to read by putting multiple key-value pairs of the `select` statements in the same line.\n- First, thanks for your comment. Using `select` is not an important requirement. i just used it to get specific data without returning id needed relation( password in the User table is different), if no requirements, is it correct to use `include` ? I think the code will be more concise than select. I was just wondering if there is a function that Prisma provides or if there is another db-level approach! @TasinIshmam\n- Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.\n- The method you suggested looks very good. I knew delete method , but i didn't think of it.. thank you , I hope that is excluded from schema is provided soon.\n- Happy to help. Please feel free to join our slack to get regular feature updates or ask if you have any questions!","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":274,"estimatedTokens":1775}}246{"id":"stack-71554571","source":"stackoverflow","questionId":71554571,"title":"How to store image into PostgreSQL using Prisma 2 and NodeJS?","tags":["node.js","postgresql","prisma"],"text":"Title: How to store image into PostgreSQL using Prisma 2 and NodeJS?\nTags: node.js, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nGood day everyone, i was looking for a similar that i can refer to, but sadly i wasn't found yet until now. Hope someone would give me some guidances on it...\n\nI'm using filepond to send the api request, and use the prisma 2 client to store it\n\nThank you!\n\n========================================\n\nTop Answer:\nI had this in my project for setting logo\n\n```\nconst eventSetLogo = (e: React.ChangeEvent) => {\n const file = e.target.files?.item(0);\n\n if (file) {\n const size = file.size;\n\n if (size > FILE_MAX_SIZE) {\n alert(\"Your file can be maximum 100kb in size.\");\n props.setLogo(undefined);\n return\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/FileReader\n const reader = new FileReader();\n // The readAsDataURL method of the FileReader interface is used to read the contents\n // of the specified Blob or File. When the read operation is finished, the readyState\n // becomes DONE, and the loadend is triggered. At that time, the result attribute\n // contains the data as `enter code here`a data: URL representing the file's data as a base64 encoded string.\n // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL\n reader.readAsDataURL(file as Blob);\n\n // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/loadend_event\n reader.onloadend = () => {\n // CREATE BASE64 STRING\n // https://en.wikipedia.org/wiki/Base64\n // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result\n const file64 = reader.result;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/FileList/item\n props.setLogo(file64 as string);\n };\n\n // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/error_event\n reader.onerror = () => {\n console.error(reader.error);\n };\n }\n };\n```\n\n========================================\n\nCode:\n```text\nconst eventSetLogo = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const file = e.target.files?.item(0);\n\n    if (file) {\n      const size = file.size;\n\n      if (size > FILE_MAX_SIZE) {\n        alert(\"Your file can be maximum 100kb in size.\");\n        props.setLogo(undefined);\n        return\n      }\n\n      // https://developer.mozilla.org/en-US/docs/Web/API/FileReader\n      const reader = new FileReader();\n      // The readAsDataURL method of the FileReader interface is used to read the contents\n      // of the specified Blob or File. When the read operation is finished, the readyState\n      // becomes DONE, and the loadend is triggered. At that time, the result attribute\n      // contains the data as `enter code here`a data: URL representing the file's data as a base64 encoded string.\n      // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL\n      reader.readAsDataURL(file as Blob);\n\n      // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/loadend_event\n      reader.onloadend = () => {\n        // CREATE BASE64 STRING\n        // https://en.wikipedia.org/wiki/Base64\n        // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result\n        const file64 = reader.result;\n\n        // https://developer.mozilla.org/en-US/docs/Web/API/FileList/item\n        props.setLogo(file64 as string);\n      };\n\n      // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/error_event\n      reader.onerror = () => {\n        console.error(reader.error);\n      };\n    }\n  };\n```\n\n========================================\n\nComments:\n- Thank you for your suggestion! i was solved it by using cloudinary api and store the image url to postgresql\n- Amazing! Glad you were able to solve it\n- Why is this answer accepted, it does not answer the question, merely gives a good practice\n- Yeah, I'm specifically looking for a way to handle this on premise, without a cloud involved.","metadata":{"transformedAt":"2026-08-18T18:33:14.841Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":108,"estimatedTokens":961}}247{"id":"stack-52173791","source":"stackoverflow","questionId":52173791,"title":"Correct way to declare fields for Prisma provided by GraphQL Yoga but not required in resolver","tags":["graphql","prisma"],"text":"Title: Correct way to declare fields for Prisma provided by GraphQL Yoga but not required in resolver\nTags: graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI've been trying to find some documentation on this on the Prisma websites but to be honest it's a bit difficult to find very detailed use cases there, especially when the problem is as difficult to describe as this one is.\n\nI have the situation where my front end sends a mutation request to `createPosting` on my GraphQL-Yoga server with the fields `positionTitle, employmentType, description, requirements, customId, expiresAt` (I have thoroughly tested that this works as expected). I want to add a `createdAt` field before creating the node on the Prisma service.\n\nIn my GraphQL-Yoga server I have a datamodel.graphql that includes the following:\n\n```\ntype Posting {\n id: ID! @unique\n customId: String! @unique\n offeredBy: Employer!\n postingTitle: String!\n positionTitle: String!\n employmentType: EmploymentType!\n status: PostingStatus!\n description: String\n requirements: String\n applications: [Application!]!\n createdAt: DateTime!\n expiresAt: DateTime!\n}\n```\n\nMy schema.graphql has this under Mutations:\n\n```\ncreatePosting(postingTitle: String!,\n positionTitle: String!,\n employmentType: String!,\n description: String!,\n requirements: String!,\n customId: String!,\n expiresAt: DateTime!,\n status: PostingStatus): Posting!\n```\n\nFinally in my createPosting resolver I attempt to mutate the Prisma backend like this:\n\n```\nconst result = await context.prisma.mutation.createPosting({\n data: {\n offeredBy: { connect: { name: context.req.name} },\n postingTitle: args.postingTitle,\n positionTitle: args.positionTitle,\n employmentType: args.employmentType,\n description: args.description,\n requirements: args.requirements,\n customId: args.customId,\n createdAt: new Date().toISOString(),\n expiresAt: expiresAt,\n status: args.status || 'UPCOMING'\n }\n })\n```\n\nWhen I try to run this from my front-end I get the following error on the server: \n\n`Error: Variable '$_v0_data' expected value of type 'PostingCreateInput!' but got: {\"customId\":\"dwa\",\"postingTitle\":\"da\",\"positionTitle\":\"da\",\"employmentType\":\"PART_TIME\",\"status\":\"UPCOMING\",\"description\":\"dada\",\"requirements\":\"dadada\",\"expiresAt\":\"2018-09-27T00:00:00.000Z\",\"createdAt\":\"2018-09-04T20:29:10.745Z\",\"offeredBy\":{\"connect\":{\"name\":\"NSB\"}}}. Reason: 'createdAt' Field 'createdAt' is not defined in the input type 'PostingCreateInput'.`\n\nFrom this error message I would assume that my Prisma service for some reason does not know about createdAt, as I recently added this field, but when I inspect the type Posting and the PostingCreateInput in the GraphQL playground on the Prisma host I find the field createdAt! in both those places.\n\nI tried deleting the generated prisma.graphql and deploying again for a fresh file but that did not work. And when I inspected prisma.graphql, PostingCreateInput did indeed miss the createdAt field, even though the Prisma server seems to have it.\n\nIf anyone can point me in the right direction as to what is wrong, or give me a better idea of how to set up variables that should be stored in the database but created in my Yoga-server as opposed to in front-end I would be very appreciative :)\n\nAlthough this question might seem a bit specific I believe the idea of creating data for the fields during on the server should be possible before creating nodes, but at the moment I'm struggling with wrapping my head around how to do it.\n\nTLDR; Want to create a `createdAt:DateTime` field on my GraphQL-Yoga server on a resolver before sending a create request to my Prisma service.\n\n========================================\n\nCode:\n```text\ntype Posting {\n  id: ID! @unique\n  customId: String! @unique\n  offeredBy: Employer!\n  postingTitle: String!\n  positionTitle: String!\n  employmentType: EmploymentType!\n  status: PostingStatus!\n  description: String\n  requirements: String\n  applications: [Application!]!\n  createdAt: DateTime!\n  expiresAt: DateTime!\n}\n```\n\n```text\ncreatePosting(postingTitle: String!,\n    positionTitle: String!,\n    employmentType: String!,\n    description: String!,\n    requirements: String!,\n    customId: String!,\n    expiresAt: DateTime!,\n    status: PostingStatus): Posting!\n```\n\n```text\nconst result = await context.prisma.mutation.createPosting({\n    data: {\n      offeredBy: { connect: { name: context.req.name} },\n      postingTitle: args.postingTitle,\n      positionTitle: args.positionTitle,\n      employmentType: args.employmentType,\n      description: args.description,\n      requirements: args.requirements,\n      customId: args.customId,\n      createdAt: new Date().toISOString(),\n      expiresAt: expiresAt,\n      status: args.status || 'UPCOMING'\n    }\n  })\n```\n\n```text\ncreatePosting\n```\n\n```text\npositionTitle, employmentType, description, requirements, customId, expiresAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nError: Variable '$_v0_data' expected value of type 'PostingCreateInput!' but got: {\"customId\":\"dwa\",\"postingTitle\":\"da\",\"positionTitle\":\"da\",\"employmentType\":\"PART_TIME\",\"status\":\"UPCOMING\",\"description\":\"dada\",\"requirements\":\"dadada\",\"expiresAt\":\"2018-09-27T00:00:00.000Z\",\"createdAt\":\"2018-09-04T20:29:10.745Z\",\"offeredBy\":{\"connect\":{\"name\":\"NSB\"}}}. Reason: 'createdAt' Field 'createdAt' is not defined in the input type 'PostingCreateInput'.\n```\n\n```text\ncreatedAt:DateTime\n```\n\n```text\ncreatedAt\n```\n\n```text\ncreatedDate\n```\n\n```text\ncreatedAt\n```\n\n```text\norderBy\n```\n\n```text\nReason: 'createdAt' Field 'createdAt' is not defined in the input type 'PostingCreateInput'.\n```\n\n```text\ncreatedAt\n```\n\n========================================\n\nComments:\n- saved me, dude!\n- @Aquib glad to hear! I would have preferred it if the library threw an error or warning @_@","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":171,"estimatedTokens":1441}}248{"id":"stack-53143743","source":"stackoverflow","questionId":53143743,"title":"Mutation with list of strings Variable \"$_v0_data\" got invalid value Graphql Node.js","tags":["node.js","express","graphql","graphql-js","prisma"],"text":"Title: Mutation with list of strings Variable \"$_v0_data\" got invalid value Graphql Node.js\nTags: node.js, express, graphql, graphql-js, prisma\nSource: Stack Overflow\n\nQuestion:\nI have this simple mutation that works fine\n\n```\ntype Mutation {\n addJob(\n url: String!\n description: String!\n position: String!\n company: String!\n date: DateTime!\n tags: [String!]!\n ): Job\n}\n```\n\nMutation Resolver\n\n```\nfunction addJob(parent, args, context, info) {\n\n console.log('Tags => ', args.tags)\n // const userId = getUserId(context)\n return context.db.mutation.createJob(\n {\n data: {\n position: args.position,\n componay: args.company,\n date: args.date,\n url: args.url,\n description: args.description,\n tags: args.tags\n }\n },\n info\n )\n}\n```\n\nhowever, once I tried to put an array of strings(tags) as you see above I I can't get it to work and I got this error \n\n```\nError: Variable \"$_v0_data\" got invalid value { ... , tags: [\"devops\", \"aws\"] }; Field \"0\" is not defined by type JobCreatetagsInput at value.tags.\n```\n\nIf I assigned an empty array to tags in the mutation there is no problem, however if I put a single string value [\"DevOps\"] for example i get the error\n\n========================================\n\nCode:\n```text\ntype Mutation {\n    addJob(\n        url: String!\n        description: String!\n        position: String!\n        company: String!\n        date: DateTime!\n        tags: [String!]!\n    ): Job\n}\n```\n\n```text\nfunction addJob(parent, args, context, info) {\n\n    console.log('Tags => ', args.tags)\n    // const userId = getUserId(context)\n    return context.db.mutation.createJob(\n        {\n            data: {\n                position: args.position,\n                componay: args.company,\n                date: args.date,\n                url: args.url,\n                description: args.description,\n                tags: args.tags\n            }\n        },\n        info\n    )\n}\n```\n\n```text\nError: Variable \"$_v0_data\" got invalid value { ... , tags: [\"devops\", \"aws\"] }; Field \"0\" is not defined by type JobCreatetagsInput at value.tags.\n```\n\n```text\nfunction addJob(parent, args, context, info) {\n    return context.db.mutation.createJob(\n        {\n            data: {\n                position: args.position,\n                componay: args.company,\n                date: args.date,\n                url: args.url,\n                description: args.description,\n                tags: { set: args.tags }\n            }\n        },\n        info\n    )\n}\n```\n\n========================================\n\nComments:\n- please add the code for the mutation\n- @Peter Added it.\n- Did you change your mutation schema recently? Did you `prisma deploy`? It seems like the `type JobCreatetagsInput` is not expecting this `String` type.\n- @Elfayer No, it's not changed at all and if I tried Prisma deploy the schema is up to date, and about this is the JobCreatetagsInput , input JobCreatetagsInput { set: [String!] }\n- Thanks for sharing, works as a charm is not clear about this in the doc.\n- @Merlyn007 glad it helped ^^","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":119,"estimatedTokens":754}}249{"id":"stack-51915695","source":"stackoverflow","questionId":51915695,"title":"GraphQL: Updating an array","tags":["javascript","typescript","graphql","prisma"],"text":"Title: GraphQL: Updating an array\nTags: javascript, typescript, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm having some issues updating an array in the resolver. I'm building with `typescript`.\n\n### Description\n\nI have in the `datamodel.graphql` for `Prisma`:\n\n```\ntype Service @model {\n id: ID! @unique\n title: String\n content: String\n createdAt: DateTime!\n updatedAt: DateTime!\n comments: [Comment!]! // Line to be seen here\n author: User!\n offer: Offer\n isPublished: Boolean! @default(value: \"false\")\n type: [ServiceType!]!\n}\n\ntype Comment @model {\n id: ID! @unique\n author: User! @relation(name: \"WRITER\")\n service: Service!\n message: String!\n}\n```\n\nThe `Prisma` is connected to the `GraphQl` server and in this one, I defined the mutation :\n\n```\ncommentService(id: String!, comment: String!): Service!\n```\n\nSo comes the time for implementing the resolver for the given mutation and I'm doing this :\n\n```\nasync commentService(parent, {id, comment}, ctx: Context, info) {\n const userId = getUserId(ctx);\n const service = await ctx.db.query.service({\n where: {id}\n });\n if (!service) {\n throw new Error(`Service not found or you're not the author`)\n }\n\n const userComment = await ctx.db.mutation.createComment({\n data: {\n message: comment,\n service: {\n connect: {id}\n },\n author: {\n connect: {id:userId}\n },\n }\n });\n\n return ctx.db.mutation.updateService({\n where: {id},\n data: {\n comments: {\n connect: {id: userComment.id}\n }\n }\n })\n}\n```\n\n### The problem :\n\nThe only thing I'm receiving when querying the playground is `null` instead of the comment I've given.\n\nThanks for reading till so far.\n\n========================================\n\nTop Answer:\nIf I understood the question correctly, you are calling this `commentService` mutation and you get null as a result? Following your logic, you should get whatever `ctx.db.mutation.updateService` resolves with, right? If you expect that to indeed be a `Service` object, then the only reason why you might not be getting it back is a missing `await`. You probably needed to write `return await ctx.db.mutation.updateService({ ...`.\n\n========================================\n\nCode:\n```text\ntype Service @model {\n    id: ID! @unique\n    title: String\n    content: String\n    createdAt: DateTime!\n    updatedAt: DateTime!\n    comments: [Comment!]! // Line to be seen here\n    author: User!\n    offer: Offer\n    isPublished: Boolean! @default(value: \"false\")\n    type: [ServiceType!]!\n}\n\ntype Comment @model {\n    id: ID! @unique\n    author: User! @relation(name: \"WRITER\")\n    service: Service!\n    message: String!\n}\n```\n\n```text\ncommentService(id: String!, comment: String!): Service!\n```\n\n```text\nasync commentService(parent, {id, comment}, ctx: Context, info) {\n    const userId = getUserId(ctx);\n    const service = await ctx.db.query.service({\n        where: {id}\n    });\n    if (!service) {\n        throw new Error(`Service not found or you're not the author`)\n    }\n\n    const userComment = await ctx.db.mutation.createComment({\n        data: {\n            message: comment,\n            service: {\n                connect: {id}\n            },\n            author: {\n                connect: {id:userId}\n            },\n        }\n    });\n\n    return ctx.db.mutation.updateService({\n        where: {id},\n        data: {\n            comments: {\n               connect: {id: userComment.id}\n            }\n        }\n    })\n}\n```\n\n```text\ntypescript\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\nPrisma\n```\n\n```text\nPrisma\n```\n\n```text\nGraphQl\n```\n\n```text\nnull\n```\n\n```text\nasync commentService(parent, {id, comment}, ctx: Context, info) {\n    const userId = getUserId(ctx);\n\n    return ctx.db.mutation.updateService({\n        where: {id},\n        data: {\n            comments: {\n               create: {\n                   message: comment,\n                   author: {\n                      connect: {id:userId}\n                   }\n               }\n            }\n        }\n    })\n}\n```\n\n```text\nnull\n```\n\n```text\ncommentService\n```\n\n```text\nService\n```\n\n```text\nComment\n```\n\n```text\ncommentService\n```\n\n```text\nctx.db.mutation.updateService\n```\n\n```text\nService\n```\n\n```text\nawait\n```\n\n```text\nreturn await ctx.db.mutation.updateService({ ...\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":226,"estimatedTokens":1052}}250{"id":"stack-69591631","source":"stackoverflow","questionId":69591631,"title":"NestJS-Prisma, How to write a DTO that matches the prisma one to many type","tags":["typescript","nestjs","prisma"],"text":"Title: NestJS-Prisma, How to write a DTO that matches the prisma one to many type\nTags: typescript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS and Prisma. I'm trying to write an API for the corresponding prisma model.\n\nHere is my prisma model:\n\n```\nmodel orderable_test {\n id Int @id @unique @default(autoincrement())\n test_name String\n test_id Int\n price Int\n is_orderable Boolean\n is_active Boolean\n orderable_bundle orderable_bundle? @relation(fields: [orderable_bundleId], references: [id])\n orderable_bundleId Int?\n }\n \n model orderable_bundle {\n id Int @id @unique @default(autoincrement())\n bundle_name String\n bundle_id Int\n price Int\n is_orderable Boolean\n is_active Boolean\n orderable_tests orderable_test[]\n }\n```\n\nFor the orderable_test, my DTO works well, the DTO for orderable_test is:\n\n```\nclass OrderableTestDTO {\n\n @ApiProperty()\n test_name: string;\n @ApiProperty()\n test_id: number;\n @ApiProperty()\n price: number;\n @ApiProperty()\n is_orderable: boolean;\n @ApiProperty()\n is_active: boolean;\n @ApiPropertyOptional({default: null})\n orderable_bundleId:number|null;\n}\n```\n\nFor the orderable_bundle DTO, I have\n\n```\nclass OrderableBundleDTO {\n @ApiProperty()\n bundle_name: string;\n @ApiProperty()\n bundle_id: number;\n @ApiProperty()\n price: number;\n @ApiProperty()\n is_orderable: boolean;\n @ApiProperty()\n is_active: boolean;\n @ApiPropertyOptional({type: () => OrderableTestDTO})\n orderable_tests: OrderableTestDTO | null\n}\n```\n\nBased on the Prisma Official Document: I will need my DTO to be like\n\n```\nconst createBundle = await prisma.bundle.create({\n data: {\n bundle_name: 'Bob',\n bundle_id: 1\n ............\n orderable_tests: {\n create: [\n {\n id: 'String',\n test_name: 'String',\n test_id: 1,\n price: 0\n .....\n },\n ],\n },\n },\n})\n```\n\nBut currently, my DTO will be look like this: missing the `create:`\n\n```\nconst createBundle = await prisma.bundle.create({\n data: {\n bundle_name: 'Bob',\n bundle_id: 1\n ............\n orderable_tests: \n {\n id: 'String',\n test_name: 'String',\n test_id: 1,\n price: 0\n .....\n },\n\n },\n },\n})\n```\n\nAnd for the auto generated Prisma type: It looks like:\n\n```\nexport type orderable_bundleCreateInput = {\n bundle_name: string\n bundle_id: number\n price: number\n is_orderable: boolean\n is_active: boolean\n orderable_tests?: orderable_testCreateNestedManyWithoutOrderable_bundleInput\n }\n\n export type orderable_testCreateNestedManyWithoutOrderable_bundleInput = {\n create?: XOR, Enumerable>\n connectOrCreate?: Enumerable\n createMany?: orderable_testCreateManyOrderable_bundleInputEnvelope\n connect?: Enumerable\n }\n```\n\nI'm really new into type script and prisma, is it possible to have a DTO that looks exactly to the auto genenated prisma type, if not, how can I add the create: before my inner orderable_test under the orderable_bundle DTO. Thanks for viewing my question!\n\n========================================\n\nCode:\n```text\nmodel orderable_test {\n      id                 Int               @id @unique @default(autoincrement())\n      test_name          String\n      test_id            Int\n      price              Int\n      is_orderable       Boolean\n      is_active          Boolean\n      orderable_bundle   orderable_bundle? @relation(fields: [orderable_bundleId], references: [id])\n      orderable_bundleId Int?\n    }\n    \n    model orderable_bundle {\n      id              Int              @id @unique @default(autoincrement())\n      bundle_name     String\n      bundle_id       Int\n      price           Int\n      is_orderable    Boolean\n      is_active       Boolean\n      orderable_tests orderable_test[]\n    }\n```\n\n```text\nclass OrderableTestDTO {\n\n    @ApiProperty()\n    test_name: string;\n    @ApiProperty()\n    test_id: number;\n    @ApiProperty()\n    price: number;\n    @ApiProperty()\n    is_orderable: boolean;\n    @ApiProperty()\n    is_active: boolean;\n    @ApiPropertyOptional({default: null})\n    orderable_bundleId:number|null;\n}\n```\n\n```text\nclass OrderableBundleDTO {\n    @ApiProperty()\n    bundle_name: string;\n    @ApiProperty()\n    bundle_id: number;\n    @ApiProperty()\n    price: number;\n    @ApiProperty()\n    is_orderable: boolean;\n    @ApiProperty()\n    is_active: boolean;\n    @ApiPropertyOptional({type: () => OrderableTestDTO})\n    orderable_tests: OrderableTestDTO | null\n}\n```\n\n```text\nconst createBundle = await prisma.bundle.create({\n  data: {\n    bundle_name: 'Bob',\n    bundle_id: 1\n    ............\n    orderable_tests: {\n      create: [\n        {\n          id: 'String',\n          test_name: 'String',\n          test_id: 1,\n      price: 0\n          .....\n        },\n      ],\n    },\n  },\n})\n```\n\n```text\nconst createBundle = await prisma.bundle.create({\n  data: {\n    bundle_name: 'Bob',\n    bundle_id: 1\n    ............\n    orderable_tests: \n        {\n          id: 'String',\n          test_name: 'String',\n          test_id: 1,\n      price: 0\n          .....\n        },\n\n    },\n  },\n})\n```\n\n```text\nexport type orderable_bundleCreateInput = {\n    bundle_name: string\n    bundle_id: number\n    price: number\n    is_orderable: boolean\n    is_active: boolean\n    orderable_tests?: orderable_testCreateNestedManyWithoutOrderable_bundleInput\n  }\n\n  export type orderable_testCreateNestedManyWithoutOrderable_bundleInput = {\n    create?: XOR<Enumerable<orderable_testCreateWithoutOrderable_bundleInput>, Enumerable<orderable_testUncheckedCreateWithoutOrderable_bundleInput>>\n    connectOrCreate?: Enumerable<orderable_testCreateOrConnectWithoutOrderable_bundleInput>\n    createMany?: orderable_testCreateManyOrderable_bundleInputEnvelope\n    connect?: Enumerable<orderable_testWhereUniqueInput>\n  }\n```\n\n```text\ncreate:\n```\n\n```text\nexport type orderable_bundleUncheckedCreateInput = {\n    id?: number\n    bundle_name: string\n    bundle_id: number\n    price: number\n    is_orderable: boolean\n    is_active: boolean\n    order_infoId?: number | null\n    orderable_tests?: orderable_testUncheckedCreateNestedManyWithoutOrderable_bundleInput\n  }\n\n  export type orderable_testUncheckedCreateNestedManyWithoutOrderable_bundleInput = {\n    create?: XOR<Enumerable<orderable_testCreateWithoutOrderable_bundleInput>, Enumerable<orderable_testUncheckedCreateWithoutOrderable_bundleInput>>\n    connectOrCreate?: Enumerable<orderable_testCreateOrConnectWithoutOrderable_bundleInput>\n    createMany?: orderable_testCreateManyOrderable_bundleInputEnvelope\n    connect?: Enumerable<orderable_testWhereUniqueInput>\n  }\n\n  export type orderable_testCreateWithoutOrderable_bundleInput = {\n    test_name: string\n    test_id: number\n    price: number\n    is_orderable: boolean\n    is_active: boolean\n  }\n  .........\n```\n\n```text\nimport {ApiExtraModels,ApiProperty} from '@nestjs/swagger'\nimport {CreateOrderInfoDto} from './create-orderInfo.dto'\nimport {ConnectOrderInfoDto} from './connect-orderInfo.dto'\n\nexport class CreateOrderableBundleOrderInfoRelationInputDto {\ncreate?: CreateOrderInfoDto;\nconnect?: ConnectOrderInfoDto;\n}\n\n@ApiExtraModels(CreateOrderInfoDto,ConnectOrderInfoDto,CreateOrderableBundleOrderInfoRelationInputDto)\nexport class CreateOrderableBundleDto {\n@ApiProperty()\nbundle_name: string;\n@ApiProperty()\nbundle_id: number;\n@ApiProperty()\nprice: number;\n@ApiProperty()\nis_orderable: boolean;\n@ApiProperty()\nis_active: boolean;\n@ApiProperty()\norder_info: CreateOrderableBundleOrderInfoRelationInputDto;\n}\n\nexport class CreateOrderInfoDto {\nsample_id: number;\nsample_barcode: number;\n}\n\n  export class ConnectOrderInfoDto {\nid?: number;\nsample_id?: number;\nsample_barcode?: number;\n  }\n```\n\n========================================\n\nComments:\n- I think you copy-pasted the wrong information in some of the code snippets. Could you take a look (You posted both your schema and the create query twice). Your problem isn't super clear to me, could you try and clarify a bit better? Why can't you just use the auto-generated prisma types?\n- Thanks for the comment, I just post my DTO (previously, I mistakenly post the model as the dto). My question is whether it's possible to create a DTO class just like those auto generated types which can automatically turn to create,connect,connectORCreate depends on the logic. I would like to use DTO other than those automatically generated types because in DTO, I can apply pipe, validator or guards to it which is more flexible.\n- Hey sorry for the late reply, I was a bit busy yesterday. I took a look at your solution. Here's a library that might also work: github.com/tpdewolf/prisma-nestjs-dto-generator if you don't want to generate the DTOs by hand. (I can't comment on how well maintained this will be moving forward though :/ )\n- @TasinIshmam Thanks for sharing this package. It seems very helpful. I was confused at the start because NestJS official website does not tell how to write a DTO that can fit the relational model well and I cant not find any article or documents about this part. Most of NestJS- Prisma tutorial articles are just simple relation or no relation models.\n- Happy to help 😃","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":337,"estimatedTokens":2238}}251{"id":"stack-75430542","source":"stackoverflow","questionId":75430542,"title":"add triggers manually inside my migrations with prisma ORM","tags":["database","postgresql","triggers","orm","prisma"],"text":"Title: add triggers manually inside my migrations with prisma ORM\nTags: database, postgresql, triggers, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to create triggers using postgresql with *prisma* as ORM\nbut it seems that it haven't supported triggers yet.\nand I found this answer ,but i don't want to create my triggers logic in the server level (using middlewares).\n\nnow I am asking, can i make my triggers manually inside my database migrations as a migration level, or it may cause some problems?\n\nfor example i have the following migrations inside my application\n\n```\n├── prisma\n│   ├── migrations\n│   │   ├── 20230202011931_initial\n│   │   │   └── migration.sql\n│   │   ├── 20230202012555_default_to_created_at\n│   │   │   └── migration.sql\n│   │   ├── 20230202130457_mapping\n│   │   │   └── migration.sql\n│   │   └── migration_lock.toml\n│   └── schema.prisma\n```\n\ncan i choose one of these files to add my triggers inside or just create another file and add my triggers inside it?\n\n========================================\n\nTop Answer:\nPrisma provides a baselining feature - that is, describing a database state before any Prisma migration was applied. It is done by providing an initial migration file, which serves as a baseline.\n\nYou can edit the initial migration to include schema elements that cannot be represented in the Prisma schema - such as stored procedures or triggers. However, there is a caveat - adding triggers or procedures which should refer to entities created in following Prisma migrations doesn't seem to be feasible that way.\n\nDocumentation link: Baselining a database\n\n========================================\n\nCode:\n```text\n├── prisma\n│   ├── migrations\n│   │   ├── 20230202011931_initial\n│   │   │   └── migration.sql\n│   │   ├── 20230202012555_default_to_created_at\n│   │   │   └── migration.sql\n│   │   ├── 20230202130457_mapping\n│   │   │   └── migration.sql\n│   │   └── migration_lock.toml\n│   └── schema.prisma\n```\n\n```text\n--create-only\n```\n\n```text\nnpx prisma migrate dev --create-only\n```\n\n```text\nnpx prisma migrate dev\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":521}}252{"id":"stack-74541839","source":"stackoverflow","questionId":74541839,"title":"Prisma upsert and delete old relations","tags":["typescript","orm","prisma"],"text":"Title: Prisma upsert and delete old relations\nTags: typescript, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a project that is composed on `Posts` and each post can have a collection of `Tags`. I'm trying to enable an edit feature that allows Post tags to be updates / added / removed. Currently, my query upserts these tags, but I'm experiencing some trouble caused by the deletion aspect. Any time new tags are created, since they have no ID at the time, they are deleted immediately.\n\n```\nawait Prisma.post.update({\n where: {\n id: postId,\n },\n data: {\n title,\n content,\n updatedAt: new Date(),\n tags: {\n // Upsert tags, remove tags that are not in the request\n upsert: tags.map((tag) => ({\n where: {\n id: tag.id ? tag.id : \"0\",\n },\n create: {\n name: tag.name,\n color: tag.color,\n creator: {\n connect: {\n id: session.user.id,\n },\n },\n },\n update: {\n name: tag.name,\n color: tag.color,\n },\n })),\n deleteMany: {\n id: {\n notIn: tags.map((tag) => tag.id ?? \"0\"),\n },\n },\n },\n },\n include: {\n tags: true,\n },\n });\n```\n\nI've attempted various solutions such as keying on the name or other properties (e.g. name AND color). None of these seem to fix the issue, as they end up duplicating tags and causing similar bugs.\n\nHere are the schema I'm using my my Post and Tag models.\n\n`Post`\n\n```\nmodel Post {\n id String @id @default(uuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n deletedAt DateTime?\n\n title String\n content String\n authorId String\n author User @relation(fields: [authorId], references: [id])\n comments Comment[]\n tags Tag[]\n}\n```\n\n`Tag`\n\n```\nmodel Tag {\n id String @id @default(uuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n name String\n color String\n creatorId String\n creator User @relation(fields: [creatorId], references: [id])\n posts Post[]\n}\n```\n\nIf someone could point me in the right direction as to how one handles a situation like this, I would greatly appreciate it.\n\n========================================\n\nCode:\n```text\nawait Prisma.post.update({\n            where: {\n                id: postId,\n            },\n            data: {\n                title,\n                content,\n                updatedAt: new Date(),\n                tags: {\n                    // Upsert tags, remove tags that are not in the request\n                    upsert: tags.map((tag) => ({\n                        where: {\n                            id: tag.id ? tag.id : \"0\",\n                        },\n                        create: {\n                            name: tag.name,\n                            color: tag.color,\n                            creator: {\n                                connect: {\n                                    id: session.user.id,\n                                },\n                            },\n                        },\n                        update: {\n                            name: tag.name,\n                            color: tag.color,\n                        },\n                    })),\n                    deleteMany: {\n                        id: {\n                            notIn: tags.map((tag) => tag.id ?? \"0\"),\n                        },\n                    },\n                },\n            },\n            include: {\n                tags: true,\n            },\n        });\n```\n\n```text\nmodel Post {\n    id        String    @id @default(uuid())\n    createdAt DateTime  @default(now())\n    updatedAt DateTime  @updatedAt\n    deletedAt DateTime?\n\n    title    String\n    content  String\n    authorId String\n    author   User      @relation(fields: [authorId], references: [id])\n    comments Comment[]\n    tags     Tag[]\n}\n```\n\n```text\nmodel Tag {\n    id        String   @id @default(uuid())\n    createdAt DateTime @default(now())\n    updatedAt DateTime @updatedAt\n\n    name      String\n    color     String\n    creatorId String\n    creator   User   @relation(fields: [creatorId], references: [id])\n    posts     Post[]\n}\n```\n\n```text\nPosts\n```\n\n```text\nTags\n```\n\n```text\nPost\n```\n\n```text\nTag\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"interactiveTransactions\"]\n}\n```\n\n```js\n// Remove <Post> if you aren't in typescript\nawait prisma.$transaction<Post>(async (trx) => {\n  const existingTags = tags.filter(({ id }) => id);\n  const newTags = tags.filter(({ id }) => !id);\n\n  await trx.tag.deleteMany({\n    where: {\n      id: {\n        notIn: existingTags.map(({ id }) => id),\n      },\n    },\n  });\n  // Update the existing tags\n  await Promise.all(\n    tags.map((tag) =>\n      trx.tag.update({\n        where: {\n          id: tag.id,\n        },\n        data: {\n          color: tag.color,\n          name: tag.name,\n        },\n      })\n    )\n  );\n  await trx.tag.createMany({\n    data: newTags.map((tag) => ({\n      ...tag,\n      creator: {\n        connect: {\n          id: session.user.id,\n        },\n      },\n    })),\n  });\n  return trx.post.update({\n    where: {\n      id: postId,\n    },\n    data: {\n      title,\n      content,\n      updatedAt: new Date(),\n    },\n    include: {\n      tags: true,\n    },\n  });\n});\n```\n\n```text\nschema.prisma\n```\n\n```text\ninteractiveTransactions\n```\n\n========================================\n\nComments:\n- Hello, could you your post and tags schema please\n- @Pompedup Sure, I've gone ahead and updated the post with them. Also, if it's worth noting I am using Postgres.\n- This is super helpful, I didn't know about transactions beforehand. I was able to use these concepts to get the behavior I desired. In my case, I removed the delete, used `promise.all` to create and connect new tags (you cannot connect using createMany), and finally, I used `update` with `set` on the tags. Thanks a ton!","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":254,"estimatedTokens":1424}}253{"id":"stack-68583833","source":"stackoverflow","questionId":68583833,"title":"prisma create with nested connect throws error","tags":["javascript","postgresql","apollo-server","prisma","prisma-graphql"],"text":"Title: prisma create with nested connect throws error\nTags: javascript, postgresql, apollo-server, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm running into a problem, where connecting a model to multiple items in another model, in a `create` call seems to throw the following error:\n\n### The error:\n\n```\nInvalid `prisma.movie.create()` invocation:\nError occurred during query execution:\nConnectorError(ConnectorError {\nuser_facing_error: None, kind: QueryError(Error {\n kind: Db, cause: Some(DbError {\n severity: \"ERROR\", parsed_severity: None, code: SqlState(\"42601\"),\n message: \"syntax error at or near \\\"ON\\\"\", detail: None, hint: None,\n position: Some(Original(93)), where_: None, schema: None, table: None,\n column: None, datatype: None, constraint: None, \n file: Some(\"scan.l\"), line: Some(1006), routine: Some(\"scanner_yyerror\") \n })\n }) \n})\n```\n\n### The code responsible for the transaction:\n\n```\nconst genresData = genres.map((genre) => ({ name: genre.name }));\nawait prisma.movie.create({\n data: {\n title: details.title,\n description: details.overview,\n // ...\n genres: {\n connect: genresData,\n },\n },\n select: {\n tmdbId: true,\n title:true,\n // ...\n },\n });\n```\n\nassuming that the `Genre` model has a unique field, `name`.\n\nthe bizarre part is that everything seems to be working fine on my local machine but not on the server hosting my app.\n\n========================================\n\nTop Answer:\n**I fixed it by removing \":6543/postgres\" from the end of my Database Url string.**\n\n```\nBefore: \n \nDATABASE_URL=\"postgres://postgres.cbdysefhsdfknrssdfxfsplka:password@aws-0-us-west-1.pooler.supabase.com:6543/postgres\"\n\nAfter:\n\nDATABASE_URL=\"postgres://postgres.cbdhekfhcknrsdxfplka:password@aws-0-us-west-1.pooler.supabase.com\n```\n\n========================================\n\nCode:\n```text\nInvalid `prisma.movie.create()` invocation:\nError occurred during query execution:\nConnectorError(ConnectorError {\nuser_facing_error: None, kind: QueryError(Error {\n kind: Db, cause: Some(DbError {\n    severity: \"ERROR\", parsed_severity: None, code: SqlState(\"42601\"),\n    message: \"syntax error at or near \\\"ON\\\"\", detail: None, hint: None,\n    position: Some(Original(93)), where_: None, schema: None, table: None,\n    column: None, datatype: None, constraint: None, \n    file: Some(\"scan.l\"), line: Some(1006), routine: Some(\"scanner_yyerror\") \n    })\n }) \n})\n```\n\n```js\nconst genresData = genres.map((genre) => ({ name: genre.name }));\nawait prisma.movie.create({\n            data: {\n                title: details.title,\n                description: details.overview,\n                // ...\n                genres: {\n                    connect: genresData,\n                },\n            },\n            select: {\n                tmdbId: true,\n                title:true,\n                // ...\n            },\n        });\n```\n\n```text\ncreate\n```\n\n```text\nGenre\n```\n\n```text\nname\n```\n\n```text\nBefore:  \n  \nDATABASE_URL=\"postgres://postgres.cbdysefhsdfknrssdfxfsplka:password@aws-0-us-west-1.pooler.supabase.com:6543/postgres\"\n\nAfter:\n\nDATABASE_URL=\"postgres://postgres.cbdhekfhcknrsdxfplka:password@aws-0-us-west-1.pooler.supabase.com\n```\n\n========================================\n\nComments:\n- Hi, I'm from Prisma. There seems to be an existing issue about this in the Prisma repo that we haven't been able to reproduce. Could you kindly do the following so we can better try to help: 1. Help us reproduce the issue in any way (code that we can run works best). 2. Provide more information about your production server/db and notably how it might differ from your dev setup. 3. Repost your problem as a comment in the issue I linked above so we can take a better look at it/keep you updated when it has been solved. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":129,"estimatedTokens":937}}254{"id":"stack-74529773","source":"stackoverflow","questionId":74529773,"title":"How to create a shared package in a Turborepo (monorepo), for prisma generated models and types?","tags":["nestjs","prisma","monorepo","yarn-workspaces","turborepo"],"text":"Title: How to create a shared package in a Turborepo (monorepo), for prisma generated models and types?\nTags: nestjs, prisma, monorepo, yarn-workspaces, turborepo\nSource: Stack Overflow\n\nQuestion:\nI am creating a monorepo using Turborepo consisting of multiple Nestjs microservices, and an API gateway to act as the request distributer. In each microservice, Postgres is used as a database and Prisma as the ORM. Each microservice has its own schema + Prisma client, so it's not a shared schema/client.\n\nWe are looking to create a shared package for things like DTOs, as well as prisma generated types and entities. The package would be shared among all microservices so if I would export the prisma generated from the microservices to the package, a cyclic dependency occurs.\n\nI am new to monorepos so this is a complex topic for me to begin with, but I am hoping someone here on Stackoverflow may have some input on the matter. Appreciate it!\n\n========================================\n\nTop Answer:\nSolution i have found is to change the default dev script from nest to ts-node.\n\nWhat i have done for constant monitoring and restarting is to use devscript as nodemon to constant tracking of file changes.\n\nthen in nodemon.json (nodemon config file) using ts-node command to run the script.\n\n```\n//package.json file\n\"dev\": \"nodemon\"\n\n//nodemon.json file\n\n{\n \"watch\": [\"src\"],\n \"ext\": \"js,ts,json\",\n \"exec\": \"ts-node src/main.ts\"\n }\n```\n\n========================================\n\nCode:\n```js\n// turbo.json\n{\n  \"$schema\": \"https://turborepo.org/schema.json\",\n  \"pipeline\": {\n    \"build\": {\n      \"dependsOn\": [\n        \"^build\",\n        \"extraBuildScriptFromPackages\",\n        \"//#extraGlobalBuildScript\"\n      ],\n// ...\n    }\n  }\n}\n```\n\n```text\n//#\n```\n\n```text\n//package.json file\n\"dev\": \"nodemon\"\n\n//nodemon.json file\n\n\n{\n   \"watch\": [\"src\"],\n   \"ext\": \"js,ts,json\",\n   \"exec\": \"ts-node src/main.ts\"\n }\n```\n\n========================================\n\nComments:\n- I wasn't able to find an exact resource which demonstrates using Turborepo with prisma in a monorepo. Have you seen this example of using Prisma with Turborepo? github.com/vercel/turbo/tree/main/examples/with-prisma\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":76,"estimatedTokens":615}}255{"id":"stack-79234117","source":"stackoverflow","questionId":79234117,"title":"TypeError: The \"payload\" argument must be of type object. Received null","tags":["mysql","object","next.js","prisma","payload"],"text":"Title: TypeError: The \"payload\" argument must be of type object. Received null\nTags: mysql, object, next.js, prisma, payload\nSource: Stack Overflow\n\nQuestion:\nMy scheme on prisma:\n\n```\n/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments\nmodel articles {\n id String @id @default(uuid())\n dealership_id String\n type String? @db.VarChar(255)\n brand String? @db.VarChar(255)\n model String? @db.VarChar(255)\n year Int?\n vin String? @db.VarChar(255)\n registration_number String? @db.VarChar(255)\n purchase_price Decimal? @db.Decimal(10, 0)\n selling_price Decimal? @db.Decimal(10, 0)\n maintenance_needed Decimal? @db.Decimal(10, 0)\n maintenance_done Decimal? @db.Decimal(10, 0)\n condition String? @db.VarChar(255)\n description String? @db.Text\n maintenance_date DateTime? @db.Timestamp(0)\n created_at DateTime? @default(now()) @db.Timestamp(0)\n updated_at DateTime? @updatedAt @db.Timestamp(0)\n\n dealership dealerships @relation(fields: [dealership_id], references: [id]) // Relación con concesionaria\n purchases purchases[] \n sales sales[] \n article_photos article_photos[] // Relación con fotos de artículo\n\n @@index([dealership_id], map: \"dealership_id\")\n}\n```\n\nand my POST method on route.ts:\n\n```\nimport prisma from '@/utils/prisma';\nimport { NextResponse } from 'next/server';\n\nexport async function POST(req: Request) {\n try {\n // Verifica si estás usando Next.js 13+\n const body = await req.json(); // Extrae el JSON del request\n\n console.log('Body recibido:', body); // Log para depuración\n\n // Validar el contenido del body\n if (!body.type || !body.brand || !body.model) {\n return NextResponse.json(\n { error: 'Todos los campos son obligatorios' },\n { status: 400 }\n );\n }\n\n // Crear artículo\n const article = await prisma.articles.create({\n data: {\n ...body,\n dealership_id: 'd9078ca9-4d6e-4d0e-a60d-dabbb3c8e5c2', // ID fijo para prueba\n },\n });\n\n return NextResponse.json(article, { status: 201 });\n } catch (error) {\n console.error('Error:', error);\n return NextResponse.json(\n { error: 'Error al registrar el artículo' },\n { status: 500 }\n );\n }\n}\n```\n\nI already tried creating new migrations in db or \"npx prisma db push\" and it didn't solve my problem, it only happens on this entity, for example, I created a dealership without problems and used its uuid to try to create an article.\n\n========================================\n\nTop Answer:\nlikely prisma is not correctly connecting to db. make sure:\n\n- db is running\n\n- schema is up to date: `npx prisma migrate`\n\n========================================\n\nCode:\n```text\n/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments\nmodel articles {\n  id                  String        @id @default(uuid())\n  dealership_id       String\n  type                String?       @db.VarChar(255)\n  brand               String?       @db.VarChar(255)\n  model               String?       @db.VarChar(255)\n  year                Int?\n  vin                 String?       @db.VarChar(255)\n  registration_number String?       @db.VarChar(255)\n  purchase_price      Decimal?      @db.Decimal(10, 0)\n  selling_price       Decimal?      @db.Decimal(10, 0)\n  maintenance_needed  Decimal?      @db.Decimal(10, 0)\n  maintenance_done    Decimal?      @db.Decimal(10, 0)\n  condition           String?       @db.VarChar(255)\n  description         String?       @db.Text\n  maintenance_date    DateTime?     @db.Timestamp(0)\n  created_at          DateTime?     @default(now()) @db.Timestamp(0)\n  updated_at          DateTime?     @updatedAt @db.Timestamp(0)\n\n  dealership          dealerships   @relation(fields: [dealership_id], references: [id]) // Relación con concesionaria\n  purchases           purchases[]   \n  sales               sales[]       \n  article_photos      article_photos[] // Relación con fotos de artículo\n\n  @@index([dealership_id], map: \"dealership_id\")\n}\n```\n\n```text\nimport prisma from '@/utils/prisma';\nimport { NextResponse } from 'next/server';\n\nexport async function POST(req: Request) {\n  try {\n    // Verifica si estás usando Next.js 13+\n    const body = await req.json(); // Extrae el JSON del request\n\n    console.log('Body recibido:', body); // Log para depuración\n\n    // Validar el contenido del body\n    if (!body.type || !body.brand || !body.model) {\n      return NextResponse.json(\n        { error: 'Todos los campos son obligatorios' },\n        { status: 400 }\n      );\n    }\n\n    // Crear artículo\n    const article = await prisma.articles.create({\n      data: {\n        ...body,\n        dealership_id: 'd9078ca9-4d6e-4d0e-a60d-dabbb3c8e5c2', // ID fijo para prueba\n      },\n    });\n\n    return NextResponse.json(article, { status: 201 });\n  } catch (error) {\n    console.error('Error:', error);\n    return NextResponse.json(\n      { error: 'Error al registrar el artículo' },\n      { status: 500 }\n    );\n  }\n}\n```\n\n```text\nnpx prisma migrate\n```\n\n```text\n.env\n```\n\n```text\n.env.local\n```\n\n========================================\n\nComments:\n- I forgot to put my json: ``` { \"type\": \"SUV\", \"brand\": \"Toyota\", \"model\": \"RAV4\", \"year\": 2023, \"vin\": \"JTMRFREV8JJ123456\", \"registration_number\": \"ABC123\", \"purchase_price\": 25000.00, \"selling_price\": 30000.00, \"condition\": \"Nuevo\", \"description\": \"SUV compacto con excelente rendimiento y tecnolog&#237;a avanzada.\", \"maintenance_needed\": 100.00, \"maintenance_done\": 50.00, \"maintenance_date\": \"2024-06-11T00:00:00Z\" } ``` with the header \"Content-Type\" \"application/json\"\n- Yes, already check that, It's just with the article scheme, I created other entities without problems","metadata":{"transformedAt":"2026-08-18T18:33:14.842Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":176,"estimatedTokens":1431}}256{"id":"stack-65534216","source":"stackoverflow","questionId":65534216,"title":"graphql query with args not working for user id","tags":["graphql","prisma","prisma-graphql","prisma2"],"text":"Title: graphql query with args not working for user id\nTags: graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nI am bamboozled. I initially created the user query and it was giving me errors that I assumed were syntax errors. But then I created an identical query for vehicles which works perfectly. I have a suspicion that it's related to the ID! type but I have run out of leads. Any help would be appreciated!\n\nHere are my typedefs and resolvers.\n\n//***TYPEDEFS***//\n\n```\ntype User {\n id: ID!\n fname: String\n lname: String\n email: String\n password: String\n vehicles: [Vehicle]\n }\n\n type Vehicle {\n id: ID!\n vin: String\n model: String\n make: String\n drivers: [User]\n }\n\n type Query {\n users: [User]\n user(id: ID!): User\n vehicles: [Vehicle]\n vehicle(vin: String): Vehicle\n }\n```\n\n//***RESOLVERS***//\n\n```\nuser: async (parent, args, context) => {\n const { id } = args\n return context.prisma.user.findUnique({\n where: {\n id,\n },\n })\n },\n vehicle: async (parent, args, context) => {\n const { vin } = args\n return context.prisma.vehicle.findUnique({\n where: {\n vin,\n }\n })\n }\n```\n\n//***QUERY***//\n\n**This one is the broken one and has the error: Got invalid value '1' on prisma.findOneUser. Provided String, expected Int\n**I've tried doing `id: \"1\"` and `user(where: {id: 1})`\n\n```\nquery {\n user(id:1){\n id\n fname\n }\n}\n```\n\n**This one works as intended\n\n```\nquery {\n vehicle(vin:\"123123123\"){\n vin\n make\n }\n}\n```\n\n//**FULL ERROR***//\n\n```\n{\n \"errors\": [\n {\n \"message\": \"\\nInvalid `prisma.user.findUnique()` invocation:\\n\\n{\\n where: {\\n id: '1'\\n ~~~\\n }\\n}\\n\\nArgument id: Got invalid value '1' on prisma.findOneUser. Provided String, expected Int.\\n\\n\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"user\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"clientVersion\": \"2.13.1\",\n \"stacktrace\": [\n \"Error: \",\n \"Invalid `prisma.user.findUnique()` invocation:\",\n \"\",\n \"{\",\n \" where: {\",\n \" id: '1'\",\n \" ~~~\",\n \" }\",\n \"}\",\n \"\",\n \"Argument id: Got invalid value '1' on prisma.findOneUser. Provided String, expected Int.\",\n \"\",\n \"\",\n \" at Document.validate (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:76090:19)\",\n \" at NewPrismaClient._executeRequest (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77796:17)\",\n \" at resource.runInAsyncScope (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77733:52)\",\n \" at AsyncResource.runInAsyncScope (async_hooks.js:188:21)\",\n \" at NewPrismaClient._request (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77733:25)\",\n \" at Object.then (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77850:39)\",\n \" at process._tickCallback (internal/process/next_tick.js:68:7)\"\n ]\n }\n }\n }\n ],\n \"data\": {\n \"user\": null\n }\n}\n```\n\n========================================\n\nCode:\n```text\ntype User {\n      id: ID!\n      fname: String\n      lname: String\n      email: String\n      password: String\n      vehicles: [Vehicle]\n    }\n\n    type Vehicle {\n      id: ID!\n      vin: String\n      model: String\n      make: String\n      drivers: [User]\n    }\n\n    type Query {\n      users: [User]\n      user(id: ID!): User\n      vehicles: [Vehicle]\n      vehicle(vin: String): Vehicle\n    }\n```\n\n```text\nuser: async (parent, args, context) => {\n        const { id } = args\n        return context.prisma.user.findUnique({\n          where: {\n            id,\n          },\n        })\n      },\n   vehicle: async (parent, args, context) => {\n        const { vin } = args\n        return context.prisma.vehicle.findUnique({\n          where: {\n            vin,\n          }\n        })\n      }\n```\n\n```text\nquery {\n  user(id:1){\n    id\n    fname\n  }\n}\n```\n\n```text\nquery {\n  vehicle(vin:\"123123123\"){\n    vin\n    make\n  }\n}\n```\n\n```text\n{\n  \"errors\": [\n    {\n      \"message\": \"\\nInvalid `prisma.user.findUnique()` invocation:\\n\\n{\\n  where: {\\n    id: '1'\\n        ~~~\\n  }\\n}\\n\\nArgument id: Got invalid value '1' on prisma.findOneUser. Provided String, expected Int.\\n\\n\",\n      \"locations\": [\n        {\n          \"line\": 2,\n          \"column\": 3\n        }\n      ],\n      \"path\": [\n        \"user\"\n      ],\n      \"extensions\": {\n        \"code\": \"INTERNAL_SERVER_ERROR\",\n        \"exception\": {\n          \"clientVersion\": \"2.13.1\",\n          \"stacktrace\": [\n            \"Error: \",\n            \"Invalid `prisma.user.findUnique()` invocation:\",\n            \"\",\n            \"{\",\n            \"  where: {\",\n            \"    id: '1'\",\n            \"        ~~~\",\n            \"  }\",\n            \"}\",\n            \"\",\n            \"Argument id: Got invalid value '1' on prisma.findOneUser. Provided String, expected Int.\",\n            \"\",\n            \"\",\n            \"    at Document.validate (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:76090:19)\",\n            \"    at NewPrismaClient._executeRequest (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77796:17)\",\n            \"    at resource.runInAsyncScope (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77733:52)\",\n            \"    at AsyncResource.runInAsyncScope (async_hooks.js:188:21)\",\n            \"    at NewPrismaClient._request (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77733:25)\",\n            \"    at Object.then (/home/atran/workspace/m4m/m4m_server/node_modules/@prisma/client/runtime/index.js:77850:39)\",\n            \"    at process._tickCallback (internal/process/next_tick.js:68:7)\"\n          ]\n        }\n      }\n    }\n  ],\n  \"data\": {\n    \"user\": null\n  }\n}\n```\n\n```text\nid: \"1\"\n```\n\n```text\nuser(where: {id: 1})\n```\n\n```text\nuser: async (parent, args, context) => {\n  const id = +args.id;\n  return context.prisma.user.findUnique({\n    where: { id }\n  });\n}\n```\n\n```text\nInt\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- If you mention an error in your post, then please also the error to help the community understand exactly what the issue is :)\n- @JosephHall oh ok! I'll add the full error in there, thanks\n- I can't believe that was the issue. I feel silly now. All the Prisma tutorials use this get Object by id example so I thought it was something deeper than that. Thank you for the help!","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":282,"estimatedTokens":1592}}257{"id":"stack-75057430","source":"stackoverflow","questionId":75057430,"title":"How to list properties of a Nestjs DTO class?","tags":["javascript","nestjs","prisma"],"text":"Title: How to list properties of a Nestjs DTO class?\nTags: javascript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI have following Nestjs DTO class:\n\n```\n// create-job-offer.dto.ts\nimport { IsOptional, IsNumber } from 'class-validator';\n\nexport class CreateJobOfferDto {\n @IsNumber()\n @IsOptional()\n mentorId: number;\n\n @IsNumber()\n @IsOptional()\n companyId: number;\n}\n```\n\nI want to obtain the list of class properties: `['mentorId', 'companyId']`.\n\nI tried so far in a controller without success following methods:\n\n```\nObject.getOwnPropertyNames(new CreateJobOfferDto());\nObject.getOwnPropertyNames(CreateJobOfferDto);\n\nObject.getOwnPropertySymbols(new CreateJobOfferDto());\nObject.getOwnPropertySymbols(CreateJobOfferDto);\n\nObject.getOwnPropertyDescriptors(CreateJobOfferDto);\nObject.getOwnPropertyDescriptors(new CreateJobOfferDto());\n\nObject.getPrototypeOf(CreateJobOfferDto);\nObject.getPrototypeOf(new CreateJobOfferDto());\n```\n\nIf I add a method, or vars in a constructor, I can get them, but not the properties.\n\nThe reason why I want to achieve this is, I am using Prisma and React, and in my React app I want to receive the list of class properties so that I can generate a model form dynamically.\n\n========================================\n\nTop Answer:\nAs well as the custom solution Mostafa proposes, you can use the `@Expose` decorator combined with the `plainToInstance` function from the `class-transformer` library.\n\n```\nimport { Expose } from 'class-transformer';\n\nexport class UserDto {\n @Expose()\n @IsNotEmpty()\n firstName: string;\n\n @Expose()\n @IsEmail()\n @IsOptional()\n public readonly email: string;\n}\n```\n\nAnd to get the keys:\n\n```\nimport { plainToInstance } from 'class-transformer';\nimport { UserDto } from './userDto';\n\nconst userDtoInstance = plainToInstance(UserDto, {});\n\nconsole.log(Object.keys(userDtoInstance));\n```\n\n========================================\n\nCode:\n```text\n// create-job-offer.dto.ts\nimport { IsOptional, IsNumber } from 'class-validator';\n\nexport class CreateJobOfferDto {\n  @IsNumber()\n  @IsOptional()\n  mentorId: number;\n\n  @IsNumber()\n  @IsOptional()\n  companyId: number;\n}\n```\n\n```text\nObject.getOwnPropertyNames(new CreateJobOfferDto());\nObject.getOwnPropertyNames(CreateJobOfferDto);\n\nObject.getOwnPropertySymbols(new CreateJobOfferDto());\nObject.getOwnPropertySymbols(CreateJobOfferDto);\n\nObject.getOwnPropertyDescriptors(CreateJobOfferDto);\nObject.getOwnPropertyDescriptors(new CreateJobOfferDto());\n\nObject.getPrototypeOf(CreateJobOfferDto);\nObject.getPrototypeOf(new CreateJobOfferDto());\n```\n\n```text\n['mentorId', 'companyId']\n```\n\n```ts\n// typescript\nclass A {\n    private readonly property1: string;\n    public readonly property2: boolean;\n}\n```\n\n```js\n// javascript\n\"use strict\";\nclass A {}\n```\n\n```js\nconst properties = Symbol('properties');\n\n// This decorator will be called for each property, and it stores the property name in an object.\nexport const Property = () => {\n  return (obj: any, propertyName: string) => {\n    (obj[properties] || (obj[properties] = [])).push(propertyName);\n  };\n};\n\n// This is a function to retrieve the list of properties for a class\nexport function getProperties(obj: any): [] {\n  return obj.prototype[properties];\n}\n```\n\n```ts\nimport { getProperties } from './decorators/property.decorator';\n\nexport class UserDto {\n  @Property()\n  @IsNotEmpty()\n  firstName: string;\n\n  @Property()\n  @IsEmail()\n  @IsOptional()\n  public readonly email: string;\n}\n```\n\n```ts\nimport { UserDto } from './dtos/user.dto';\n\ngetProperties(UserDto); // [ 'firstName', 'email' ]\n```\n\n```ts\nimport { keys } from 'ts-transformer-keys';\n\ninterface Props {\n  id: string;\n  name: string;\n  age: number;\n}\nconst keysOfProps = keys<Props>();\n\nconsole.log(keysOfProps); // ['id', 'name', 'age']\n```\n\n```text\ngetProperties\n```\n\n```text\nimport { Expose } from 'class-transformer';\n\nexport class UserDto {\n  @Expose()\n  @IsNotEmpty()\n  firstName: string;\n\n  @Expose()\n  @IsEmail()\n  @IsOptional()\n  public readonly email: string;\n}\n```\n\n```text\nimport { plainToInstance } from 'class-transformer';\nimport { UserDto } from './userDto';\n\nconst userDtoInstance = plainToInstance(UserDto, {});\n\nconsole.log(Object.keys(userDtoInstance));\n```\n\n```text\n@Expose\n```\n\n```text\nplainToInstance\n```\n\n```text\nclass-transformer\n```\n\n========================================\n\nComments:\n- great answer, thanks a lot. I'm surprise that when compiling TS to JS, it just deletes the keys, I'd would expect to initialise them as null or sth.","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":219,"estimatedTokens":1123}}258{"id":"stack-75186861","source":"stackoverflow","questionId":75186861,"title":"Prisma + Docker + NextJS - docker-componse - Where to put \"npx prisma db push\"","tags":["docker","next.js","prisma"],"text":"Title: Prisma + Docker + NextJS - docker-componse - Where to put \"npx prisma db push\"\nTags: docker, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to dockerize my app (Prisma 4.9.1, NextJS 12, PostgreSQL). The idea is, that you can clone the repo, type `docker-compose up` and everything works just fine.\n\nThe problem is: I don't know where put `npx prisma db push`. I've tried already multiple locations, but it's not working. Any ideas?\n\n**Dockerfile:**\n\n```\nFROM node:18 AS dependencies\n\nWORKDIR /app\nCOPY package.json yarn.lock ./\nRUN yarn\n\nFROM node:18 AS build\n\nWORKDIR /app\nCOPY --from=dependencies /app/node_modules ./node_modules\nCOPY . .\n\nRUN npx prisma generate\nRUN yarn build:in:docker\n\nFROM node:18 AS deploy\n\nWORKDIR /app\n\nENV NODE_ENV production\n\nCOPY --from=build /app/public ./public\nCOPY --from=build /app/package.json ./package.json\nCOPY --from=build /app/.next/standalone ./\nCOPY --from=build /app/.next/static ./.next/static\nCOPY --from=build /app/node_modules ./node_modules\nCOPY --from=build /app/prisma ./prisma\n\nEXPOSE 3000\n\nENV PORT 3000\n\nCMD [\"node\", \"server.js\"]\n```\n\n**docker-compose.yml**\n\n```\nversion: '3.9'\nservices:\n postgres:\n image: postgres:latest\n container_name: postgres\n hostname: myhost\n ports:\n - 5432:5432\n environment:\n POSTGRES_USER: root\n POSTGRES_PASSWORD: password\n POSTGRES_DB: splitmate\n volumes:\n - postgres-data:/var/lib/postgresql/data\n restart: unless-stopped\n splitmate-app:\n image: splitmate\n build:\n context: .\n dockerfile: Dockerfile\n target: deploy\n volumes:\n - postgres-data:/app/postgres-data\n environment:\n DATABASE_URL: postgresql://root:password@myhost:5432/splitmate?schema=public&connect_timeout=60\n ports:\n - 3000:3000\nvolumes:\n postgres-data:\n```\n\nThe container gets built and starts. But as soon as the code tries to access the database, I get this error:\n\n```\nfeatures-splitmate-app-1 | Invalid `prisma.account.findUnique()` invocation:\nfeatures-splitmate-app-1 | \nfeatures-splitmate-app-1 | \nfeatures-splitmate-app-1 | The table `public.Account` does not exist in the current database. {\nfeatures-splitmate-app-1 | message: '\\n' +\nfeatures-splitmate-app-1 | 'Invalid `prisma.account.findUnique()` invocation:\\n' +\nfeatures-splitmate-app-1 | '\\n' +\nfeatures-splitmate-app-1 | '\\n' +\nfeatures-splitmate-app-1 | 'The table `public.Account` does not exist in the current database.',\nfeatures-splitmate-app-1 | stack: 'Error: \\n' +\nfeatures-splitmate-app-1 | 'Invalid `prisma.account.findUnique()` invocation:\\n' +\nfeatures-splitmate-app-1 | '\\n' +\nfeatures-splitmate-app-1 | '\\n' +\nfeatures-splitmate-app-1 | 'The table `public.Account` does not exist in the current database.\\n' +\nfeatures-splitmate-app-1 | ' at RequestHandler.handleRequestError (/app/node_modules/@prisma/client/runtime/index.js:31941:13)\\n' +\nfeatures-splitmate-app-1 | ' at RequestHandler.handleAndLogRequestError (/app/node_modules/@prisma/client/runtime/index.js:31913:12)\\n' +\nfeatures-splitmate-app-1 | ' at RequestHandler.request (/app/node_modules/@prisma/client/runtime/index.js:31908:12)\\n' +\nfeatures-splitmate-app-1 | ' at async PrismaClient._request (/app/node_modules/@prisma/client/runtime/index.js:32994:16)\\n' +\nfeatures-splitmate-app-1 | ' at async getUserByAccount (/app/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29)',\nfeatures-splitmate-app-1 | name: 'Error'\nfeatures-splitmate-app-1 | }\n```\n\n========================================\n\nTop Answer:\nI found a similar solution to this answer:\n\nDockerfile\n\n```\nFROM node:18-alpine\n\n# Create app directory\nWORKDIR /app\n\n# Bundle files\nCOPY . .\n\n#Update npm \nRUN npm install -g npm@latest\n\n# Install dependencies\nRUN npm install\n\n# Expose port 3000\nEXPOSE 3000\n\n# Start app\nCMD source migrate-and-start.sh\n```\n\nmigrate-and-start.sh\n\n```\n#!/bin/sh\nnpm run build\nnpx prisma generate\nnpx prisma migrate dev --name init\nnpm run start\n```\n\nIt solves problem when prisma can't find postgres DB ready too.\n\n========================================\n\nCode:\n```text\nFROM node:18 AS dependencies\n\nWORKDIR /app\nCOPY package.json yarn.lock ./\nRUN yarn\n\nFROM node:18 AS build\n\nWORKDIR /app\nCOPY --from=dependencies /app/node_modules ./node_modules\nCOPY . .\n\nRUN npx prisma generate\nRUN yarn build:in:docker\n\nFROM node:18 AS deploy\n\nWORKDIR /app\n\nENV NODE_ENV production\n\nCOPY --from=build /app/public ./public\nCOPY --from=build /app/package.json ./package.json\nCOPY --from=build /app/.next/standalone ./\nCOPY --from=build /app/.next/static ./.next/static\nCOPY --from=build /app/node_modules ./node_modules\nCOPY --from=build /app/prisma ./prisma\n\nEXPOSE 3000\n\nENV PORT 3000\n\nCMD [\"node\", \"server.js\"]\n```\n\n```text\nversion: '3.9'\nservices:\n  postgres:\n    image: postgres:latest\n    container_name: postgres\n    hostname: myhost\n    ports:\n      - 5432:5432\n    environment:\n      POSTGRES_USER: root\n      POSTGRES_PASSWORD: password\n      POSTGRES_DB: splitmate\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    restart: unless-stopped\n  splitmate-app:\n    image: splitmate\n    build:\n      context: .\n      dockerfile: Dockerfile\n      target: deploy\n    volumes:\n      - postgres-data:/app/postgres-data\n    environment:\n      DATABASE_URL: postgresql://root:password@myhost:5432/splitmate?schema=public&connect_timeout=60\n    ports:\n      - 3000:3000\nvolumes:\n  postgres-data:\n```\n\n```text\nfeatures-splitmate-app-1  | Invalid `prisma.account.findUnique()` invocation:\nfeatures-splitmate-app-1  | \nfeatures-splitmate-app-1  | \nfeatures-splitmate-app-1  | The table `public.Account` does not exist in the current database. {\nfeatures-splitmate-app-1  |   message: '\\n' +\nfeatures-splitmate-app-1  |     'Invalid `prisma.account.findUnique()` invocation:\\n' +\nfeatures-splitmate-app-1  |     '\\n' +\nfeatures-splitmate-app-1  |     '\\n' +\nfeatures-splitmate-app-1  |     'The table `public.Account` does not exist in the current database.',\nfeatures-splitmate-app-1  |   stack: 'Error: \\n' +\nfeatures-splitmate-app-1  |     'Invalid `prisma.account.findUnique()` invocation:\\n' +\nfeatures-splitmate-app-1  |     '\\n' +\nfeatures-splitmate-app-1  |     '\\n' +\nfeatures-splitmate-app-1  |     'The table `public.Account` does not exist in the current database.\\n' +\nfeatures-splitmate-app-1  |     '    at RequestHandler.handleRequestError (/app/node_modules/@prisma/client/runtime/index.js:31941:13)\\n' +\nfeatures-splitmate-app-1  |     '    at RequestHandler.handleAndLogRequestError (/app/node_modules/@prisma/client/runtime/index.js:31913:12)\\n' +\nfeatures-splitmate-app-1  |     '    at RequestHandler.request (/app/node_modules/@prisma/client/runtime/index.js:31908:12)\\n' +\nfeatures-splitmate-app-1  |     '    at async PrismaClient._request (/app/node_modules/@prisma/client/runtime/index.js:32994:16)\\n' +\nfeatures-splitmate-app-1  |     '    at async getUserByAccount (/app/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29)',\nfeatures-splitmate-app-1  |   name: 'Error'\nfeatures-splitmate-app-1  | }\n```\n\n```text\ndocker-compose up\n```\n\n```text\nnpx prisma db push\n```\n\n```text\nFROM node:18 AS dependencies\n\nWORKDIR /app\nCOPY package.json yarn.lock ./\nRUN yarn\n\nFROM node:18 AS build\n\nWORKDIR /app\nCOPY --from=dependencies /app/node_modules ./node_modules\nCOPY . .\n\nRUN npx prisma generate\nRUN yarn build:in:docker\nCOPY migrate-and-start.sh .\nRUN chmod +x migrate-and-start.sh\n\nFROM node:18 AS deploy\n\nWORKDIR /app\n\nENV NODE_ENV production\n\nCOPY --from=build /app/public ./public\nCOPY --from=build /app/package.json ./package.json\nCOPY --from=build /app/.next/standalone ./\nCOPY --from=build /app/.next/static ./.next/static\nCOPY --from=build /app/node_modules ./node_modules\nCOPY --from=build /app/prisma ./prisma\nCOPY --from=build /app/migrate-and-start.sh .\n\nEXPOSE 3000\n\nENV PORT 3000\n\nCMD [\"./migrate-and-start.sh\"]\n```\n\n```text\n#!/bin/bash\n\nnpx prisma generate\nnpx prisma db push\nnode server.js\n```\n\n```text\nversion: '3.9'\nservices:\n  postgres:\n    image: postgres:latest\n    container_name: postgres\n    hostname: myhost\n    ports:\n      - 5432:5432\n    environment:\n      POSTGRES_USER: root\n      POSTGRES_PASSWORD: password\n      POSTGRES_DB: splitmate\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    restart: unless-stopped\n  splitmate-app:\n    image: splitmate\n    build:\n      context: .\n      dockerfile: Dockerfile\n      target: deploy\n    volumes:\n      - postgres-data:/app/postgres-data\n    environment:\n      DATABASE_URL: postgresql://root:password@myhost:5432/splitmate?schema=public&connect_timeout=60\n    ports:\n      - 3000:3000\nvolumes:\n  postgres-data:\n```\n\n```text\nFROM node:18-alpine\n\n# Create app directory\nWORKDIR /app\n\n# Bundle files\nCOPY . .\n\n#Update npm \nRUN npm install -g npm@latest\n\n# Install dependencies\nRUN npm install\n\n# Expose port 3000\nEXPOSE 3000\n\n# Start app\nCMD source migrate-and-start.sh\n```\n\n```text\n#!/bin/sh\nnpm run build\nnpx prisma generate\nnpx prisma migrate dev --name init\nnpm run start\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":359,"estimatedTokens":2225}}259{"id":"stack-72190270","source":"stackoverflow","questionId":72190270,"title":"Prisma throwing error: Ambiguous relation detected","tags":["sql","postgresql","prisma"],"text":"Title: Prisma throwing error: Ambiguous relation detected\nTags: sql, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using prisma and trying to model a referral table for my Postgres database. Not sure if the db schema is correct, but I have a table with a `referId`, `userId`: 1 to 1, and `referredUserId`: 1 to many.\n\n```\nmodel Referral {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n updatedAt DateTime @default(now())\n\n referId String // Auto Generate Random String\n\n userId Int @unique\n user User @relation(fields: [userId], references: [id])\n\n referredUsersId Int[]\n referredUsers User[] @relation(fields: [referredUsersId], references: [id])\n}\n```\n\nI'm not sure exactly how to reference these in the User model. I tried\n\n```\nReferral Referral? \nUsersReferred Referral[]\n```\n\nBut I get an error\n\nError validating model \"User\": Ambiguous relation detected\n\nWhat's the correct way to model a referral table and how can I do it in prisma?\n\n========================================\n\nCode:\n```text\nmodel Referral {\n  id        Int      @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @default(now())\n\n  referId String // Auto Generate Random String\n\n  userId Int  @unique\n  user   User @relation(fields: [userId], references: [id])\n\n  referredUsersId Int[]\n  referredUsers   User[] @relation(fields: [referredUsersId], references: [id])\n}\n```\n\n```text\nReferral        Referral? \nUsersReferred Referral[]\n```\n\n```text\nreferId\n```\n\n```text\nuserId\n```\n\n```text\nreferredUserId\n```\n\n```text\nmodel User {\n  id            String     @id\n  Referral      Referral?  @relation(\"UserReferral\")\n  UsersReferred Referral[] @relation(\"ReferredUsers\")\n}\n\nmodel Referral {\n  id              Int      @id @default(autoincrement())\n  createdAt       DateTime @default(now())\n  updatedAt       DateTime @default(now())\n  referId         String\n  userId          String   @unique\n  user            User     @relation(fields: [userId], references: [id], name: \"UserReferral\")\n  referredUsersId String\n  referredUsers   User     @relation(fields: [referredUsersId], references: [id], name: \"ReferredUsers\")\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":90,"estimatedTokens":543}}260{"id":"stack-75663635","source":"stackoverflow","questionId":75663635,"title":"Prisma Models: can autoincrement() start at 0?","tags":["postgresql","prisma"],"text":"Title: Prisma Models: can autoincrement() start at 0?\nTags: postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have `@id @default(autoincrement())` with auto-incrementation starting the `id`s from 0 instead of 1 ?\n\nIn relation to : start ids at an arbitrary number in prisma data model\n(which did not receive any answer either)\n\nI am interested to see if it is possible with `postgresql` in particular.\n\nPrisma generates the corresponding SQL :\n\n```\nCREATE TABLE \"Message\" (\n \"id\" SERIAL NOT NULL,\n \"from\" TEXT NOT NULL,\n \"content\" TEXT NOT NULL,\n \"discussionId\" INTEGER NOT NULL,\n\n CONSTRAINT \"Message_pkey\" PRIMARY KEY (\"id\")\n);\n```\n\nIs the `NOT NULL` the issue ? Would it be ok to remove it ?\n\nThat SO answer seems to at least suggest that it would be possible : https://stackoverflow.com/a/32728273/10469162\n\nAnd if it's possible, is there a reason for Prisma not to expose it ?\n\n========================================\n\nTop Answer:\nThere are a couple options available. The first and preferred is generated always as identity. Available only in versions 10 and above.\n\n```\ncreate table message (\n id integer generated always as identity \n (minvalue 0 start with 0)\n , _from text not null\n , content text not null\n , discussionid integer not null\n , constraint message_pkey primary key (id)\n);\n```\n\nThe other (and required for versions prior to 10) is not define the `id` column as serial, but manually do what serial does. Although `serial` occupies the place of data type in the ddl it is not a data type; it is actually a short for:\n\n- create a sequence,\n\n- create column of data type integer,\nset the sequence as default for column. \n\nSo:\n\n```\ncreate sequence message_id_seq\n minvalue 0\n start with 0;\n \ncreate table message (\n id integer default nextval('message_id_seq')\n , _from text not null\n , content text not null\n , discussionid integer not null\n , constraint message_pkey primary key (id)\n );\n```\n\nSee demo. Sorry, but I am unable to translate into your obscurification language (Prisma) as I am not familiar enough with it.\n\n========================================\n\nCode:\n```text\nCREATE TABLE \"Message\" (\n    \"id\" SERIAL NOT NULL,\n    \"from\" TEXT NOT NULL,\n    \"content\" TEXT NOT NULL,\n    \"discussionId\" INTEGER NOT NULL,\n\n    CONSTRAINT \"Message_pkey\" PRIMARY KEY (\"id\")\n);\n```\n\n```text\n@id @default(autoincrement())\n```\n\n```text\nid\n```\n\n```text\npostgresql\n```\n\n```text\nNOT NULL\n```\n\n```text\nmodel Task {\n  id        Int   @id @default(autoincrement())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n  title     String?\n}\n```\n\n```text\nnpx prisma  migrate dev --create-only\n```\n\n```sql\nALTER SEQUENCE \"Task_id_seq\" MINVALUE 0 START 0 RESTART 0;\n```\n\n```text\nnpx prisma  migrate dev\n```\n\n```js\nconst res = await prisma.task.create({\n  data: {\n    title: \"testing\",\n    updatedAt: new Date()\n  }\n })\n```\n\n```js\n{\n  id: 0,\n  createdAt: 2023-03-09T02:35:53.587Z,\n  updatedAt: 2023-03-09T02:35:53.532Z,\n  title: 'testing'\n}\n```\n\n```text\ncreate table message (\n      id integer generated always as identity \n                 (minvalue 0  start with 0)\n    , _from text not null\n    , content text not null\n    , discussionid integer not null\n    , constraint message_pkey primary key (id)\n);\n```\n\n```text\ncreate sequence message_id_seq\n                minvalue 0\n                start with 0;\n            \ncreate table message (\n    id integer default nextval('message_id_seq')\n    , _from text not null\n    , content text not null\n    , discussionid integer not null\n    , constraint message_pkey primary key (id)\n    );\n```\n\n```text\nid\n```\n\n```text\nserial\n```\n\n========================================\n\nComments:\n- A primary key can never be null, so NOT NULL is required. If you leave it out, the database will (re-)create this constraint anyway.\n- Thanks for the great answer. Seeing your answer, I decided to create another question for which your answer is a more direct answer : stackoverflow.com/questions/75683301/&hellip; Would you like to paste it over there so I green check it ? I have already put a link to here there\n- No that just creates a duplicate/answer question. A link is sufficient.\n- This question has received an answer on Prisma's github \"discussions\". While I am waiting for the authorization to post that answer here, here is the link : github.com/prisma/prisma/discussions/18246","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":181,"estimatedTokens":1091}}261{"id":"stack-70797220","source":"stackoverflow","questionId":70797220,"title":"Prisma DateTime format ( ISO 8601) changes to weird number","tags":["react-native","graphql","prisma"],"text":"Title: Prisma DateTime format ( ISO 8601) changes to weird number\nTags: react-native, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI use Prisma `DateTime` model field as it provides to get `createdAt`.\nSo it automatically stamped ISO 8601 format on my db.\n\n`2022-01-20T12:01:30.543Z`\n\nBut when I console.log this data on my app, it changes to weird number like `1642680090542`.\n\nWhat kind of number is this?\n\nAnd How can I change it to normal date?\n\n========================================\n\nCode:\n```text\nDateTime\n```\n\n```text\ncreatedAt\n```\n\n```text\n2022-01-20T12:01:30.543Z\n```\n\n```text\n1642680090542\n```\n\n```text\nvar date = new Date(1642680090542);\nconsole.log(date)\n```\n\n```text\nmilliseconds\n```\n\n========================================\n\nComments:\n- But when I console.log createdDate after making `const createdDate = new Date(createdAt);` it says `Date { NaN }` T_T\n- it should be var date = new Date(+1642680090542); as adding `+`. then it works! anyway thanks :)\n- why does the + fix the problem?\n- The + converts it to a number","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":51,"estimatedTokens":261}}262{"id":"stack-68976639","source":"stackoverflow","questionId":68976639,"title":"How to filter on relation in Prisma ORM","tags":["postgresql","nestjs","relation","prisma"],"text":"Title: How to filter on relation in Prisma ORM\nTags: postgresql, nestjs, relation, prisma\nSource: Stack Overflow\n\nQuestion:\nI am working currently on a course service. Users have the possibility to register and deregister for courses. The entire system is built in a microservice architecture, which means that users are managed by another service. Therefore, the data model of the course service looks like this:\n\n```\nmodel course {\n id Int @id @default(autoincrement())\n orderNumber Int @unique\n courseNumber String @unique @db.VarChar(255)\n courseName String @db.VarChar(255)\n courseOfficer String @db.VarChar(255)\n degree String @db.VarChar(255)\n ectCount Int\n faculty String @db.VarChar(255)\n isWinter Boolean @default(false)\n isSummer Boolean @default(false)\n courseDescription String? @db.VarChar(255)\n enrollmentCourse enrollmentCourse[]\n}\n\nmodel enrollmentCourse {\n id Int @id @default(autoincrement())\n userId String @db.VarChar(1024)\n course course @relation(fields: [courseId], references: [id])\n courseId Int\n}\n```\n\nI want to find all the courses in which a certain user has enrolled.\nI have written 2 queries. One goes over the courses and tries to filter on the enrollmentCourse. However, this one does not work and I get all the courses back. Whereas the second one goes over the enrollmentCourse and then uses a mapping to return the courses. This works, but I don't like this solution and would prefer the 1st query if it worked:\n(I have used this guide in order to write the first query: here)\n\n```\nconst result1 = await this.prisma.course.findMany({\n where: { enrollmentCourse: { every: { userId: user.id } } },\n include: { enrollmentCourse: true }\n});\n\nconsole.log('Test result 1: ');\nconsole.log(result1);\n\nconst result2 = await this.prisma.enrollmentCourse.findMany({\n where: { userId: user.id },\n include: { course: { include: { enrollmentCourse: true } } }\n});\n\nconsole.log('Test result 2: ');\nconsole.log(result2.map((enrollment) => enrollment.course));\n```\n\nIf now the user is not enrolled in a course the result of both queries are:\n\n```\nTest result 1:\n[\n {\n id: 2,\n orderNumber: 1,\n courseNumber: 'test123',\n courseName: 'testcourse',\n courseOfficer: 'testcontact',\n degree: 'Bachelor',\n ectCount: 5,\n faculty: 'testfaculty',\n isWinter: true,\n isSummer: false,\n courseDescription: 'test.pdf',\n enrollmentCourse: []\n }\n]\nTest result 2:\n[]\n```\n\nIf now the user has enrolled courses it looks like this:\n\n```\nTest result 1:\n[\n {\n id: 2,\n orderNumber: 1,\n courseNumber: 'test123',\n courseName: 'testcourse',\n courseOfficer: 'testcontact',\n degree: 'Bachelor',\n ectCount: 5,\n faculty: 'testfaculty',\n isWinter: true,\n isSummer: false,\n courseDescription: 'test.pdf',\n enrollmentCourse: [ [Object] ]\n }\n]\nTest result 2:\n[\n {\n id: 2,\n orderNumber: 1,\n courseNumber: 'test123',\n courseName: 'testcourse',\n courseOfficer: 'testcontact',\n degree: 'Bachelor',\n ectCount: 5,\n faculty: 'testfaculty',\n isWinter: true,\n isSummer: false,\n courseDescription: 'test.pdf',\n enrollmentCourse: [ [Object] ]\n }\n]\n```\n\nAs we can see the first query does not work correctly. Can anybody give me a hint? Is there anything that I'm missing?\n\n========================================\n\nCode:\n```text\nmodel course {\n  id                Int                @id @default(autoincrement())\n  orderNumber       Int                @unique\n  courseNumber      String             @unique @db.VarChar(255)\n  courseName        String             @db.VarChar(255)\n  courseOfficer     String             @db.VarChar(255)\n  degree            String             @db.VarChar(255)\n  ectCount          Int\n  faculty           String             @db.VarChar(255)\n  isWinter          Boolean            @default(false)\n  isSummer          Boolean            @default(false)\n  courseDescription String?            @db.VarChar(255)\n  enrollmentCourse  enrollmentCourse[]\n}\n\nmodel enrollmentCourse {\n  id       Int    @id @default(autoincrement())\n  userId   String @db.VarChar(1024)\n  course   course @relation(fields: [courseId], references: [id])\n  courseId Int\n}\n```\n\n```text\nconst result1 = await this.prisma.course.findMany({\n  where: { enrollmentCourse: { every: { userId: user.id } } },\n  include: { enrollmentCourse: true }\n});\n\nconsole.log('Test result 1: ');\nconsole.log(result1);\n\nconst result2 = await this.prisma.enrollmentCourse.findMany({\n  where: { userId: user.id },\n  include: { course: { include: { enrollmentCourse: true } } }\n});\n\nconsole.log('Test result 2: ');\nconsole.log(result2.map((enrollment) => enrollment.course));\n```\n\n```text\nTest result 1:\n[\n  {\n    id: 2,\n    orderNumber: 1,\n    courseNumber: 'test123',\n    courseName: 'testcourse',\n    courseOfficer: 'testcontact',\n    degree: 'Bachelor',\n    ectCount: 5,\n    faculty: 'testfaculty',\n    isWinter: true,\n    isSummer: false,\n    courseDescription: 'test.pdf',\n    enrollmentCourse: []\n  }\n]\nTest result 2:\n[]\n```\n\n```text\nTest result 1:\n[\n  {\n    id: 2,\n    orderNumber: 1,\n    courseNumber: 'test123',\n    courseName: 'testcourse',\n    courseOfficer: 'testcontact',\n    degree: 'Bachelor',\n    ectCount: 5,\n    faculty: 'testfaculty',\n    isWinter: true,\n    isSummer: false,\n    courseDescription: 'test.pdf',\n    enrollmentCourse: [ [Object] ]\n  }\n]\nTest result 2:\n[\n  {\n    id: 2,\n    orderNumber: 1,\n    courseNumber: 'test123',\n    courseName: 'testcourse',\n    courseOfficer: 'testcontact',\n    degree: 'Bachelor',\n    ectCount: 5,\n    faculty: 'testfaculty',\n    isWinter: true,\n    isSummer: false,\n    courseDescription: 'test.pdf',\n    enrollmentCourse: [ [Object] ]\n  }\n]\n```\n\n```text\nconst result1 = await this.prisma.course.findMany({\n  where: { enrollmentCourse: { some: { userId: user.id } } },\n  include: { enrollmentCourse: true }\n});\n```\n\n```text\nsome\n```\n\n```text\nevery\n```\n\n```text\nuser\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":240,"estimatedTokens":1445}}263{"id":"stack-77942137","source":"stackoverflow","questionId":77942137,"title":"Why am I getting a P2003 Foreign Key Constraint Prisma Error?","tags":["postgresql","prisma","next.js13","clerk"],"text":"Title: Why am I getting a P2003 Foreign Key Constraint Prisma Error?\nTags: postgresql, prisma, next.js13, clerk\nSource: Stack Overflow\n\nQuestion:\nI am building a website with NextJS, Prisma, PostgreSQL, and Clerk for authentication.\n\nI am using Clerk webhooks to send user data to my PostgreSQL database.\n\nFollowing the Clerk guide, I created an API route to receive the webhook and post the data to my database using the following Prisma model:\n\n```\nmodel User {\n id String @id @unique\n favorites Favorite[]\n reviews Review[]\n}\n```\n\nSo far, so good. Everything works great.\n\nNow, as you can see from my User model above, I want to create a Prisma Favorite model and a Review model and connect those models to the User model with a relation.\n\nHere is my Favorite model:\n\n```\nmodel Favorite {\n id String @id @default(cuid())\n\n userId String @unique\n user User @relation(fields: [userId], references: [id])\n\n listingId String\n listing Listing @relation(fields: [listingId], references: [id])\n}\n```\n\nThis is where everything breaks. When I submit the API route for managing favorites in Postman on my localhost, I get the following error:\n\n```\n{\n \"name\": \"PrismaClientKnownRequestError\",\n \"code\": \"P2003\",\n \"clientVersion\": \"5.9.1\",\n \"meta\": {\n \"modelName\": \"Favorite\",\n \"field_name\": \"Favorite_userId_fkey (index)\"\n }\n}\n```\n\nI don't understand this error. I don't have any idea what I need to do to fix it. It is especially frustrating because when I use Prisma Studio to create the favorite manually, it works beautifully and the User table shows that the User now has a Favorite associated with it.\n\nHere is the API route for handling favorites, for your reference. (The only data the POST requires is a `listingId`.)\n\n```\nimport prisma from \"@/prisma/client\";\nimport { favoriteSchema } from \"@/schemas/validationSchemas\";\nimport { auth } from \"@clerk/nextjs\";\nimport { NextRequest, NextResponse } from \"next/server\";\n\nexport async function POST(request: NextRequest) {\n const { userId } = auth();\n\n if (!userId)\n return NextResponse.json({ error: \"Not authorized\" }, { status: 401 });\n\n let body = await request.json();\n body = { userId, ...body };\n\n const validation = favoriteSchema.safeParse(body);\n\n if (!validation.success)\n return NextResponse.json(validation.error.format(), { status: 400 });\n\n const alreadyExists = await prisma.favorite.findFirst({\n where: {\n id: body.userId,\n listingId: body.listingId,\n },\n });\n\n if (alreadyExists) {\n try {\n await prisma.favorite.delete({\n where: {\n id: alreadyExists.id,\n },\n });\n return NextResponse.json(\n { success: \"Favorite removed\" },\n { status: 200 }\n );\n } catch (error) {\n return NextResponse.json(error, { status: 500 });\n }\n }\n\n try {\n const newFavorite = await prisma.favorite.create({\n data: {\n userId: body.userId,\n listingId: body.listingId,\n },\n });\n\n return NextResponse.json(newFavorite, { status: 201 });\n } catch (error) {\n return NextResponse.json(error, { status: 500 });\n }\n}\n```\n\nI have tried connecting these two tables in various ways and I can't seem to figure out why I keep getting this Foreign Key Constraint error. As I mentioned above, I am able to create the record in the Favorite table manually within Prisma Studio, and it works perfectly, but I cannot do it with the API route without getting this P2003 error.\n\nUPDATE: I tried editing my Prisma models, following Prisma's documentation, and I am still getting an error.\n\nNew models:\n\n```\nmodel User {\n id String @id @default(cuid())\n userId String @unique\n favorites Favorite[]\n reviews Review[]\n}\n\nmodel Favorite {\n id String @id @default(cuid())\n\n clerkId String\n user User @relation(fields: [clerkId], references: [userId])\n\n listingId String\n listing Listing @relation(fields: [listingId], references: [id])\n}\n```\n\nError:\n\n```\n{\n \"name\": \"PrismaClientKnownRequestError\",\n \"code\": \"P2003\",\n \"clientVersion\": \"5.9.1\",\n \"meta\": {\n \"modelName\": \"Favorite\",\n \"field_name\": \"Favorite_clerkId_fkey (index)\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmodel User {\n  id        String     @id @unique\n  favorites Favorite[]\n  reviews   Review[]\n}\n```\n\n```text\nmodel Favorite {\n  id String @id @default(cuid())\n\n  userId String @unique\n  user   User   @relation(fields: [userId], references: [id])\n\n  listingId String\n  listing   Listing @relation(fields: [listingId], references: [id])\n}\n```\n\n```text\n{\n    \"name\": \"PrismaClientKnownRequestError\",\n    \"code\": \"P2003\",\n    \"clientVersion\": \"5.9.1\",\n    \"meta\": {\n        \"modelName\": \"Favorite\",\n        \"field_name\": \"Favorite_userId_fkey (index)\"\n    }\n}\n```\n\n```text\nimport prisma from \"@/prisma/client\";\nimport { favoriteSchema } from \"@/schemas/validationSchemas\";\nimport { auth } from \"@clerk/nextjs\";\nimport { NextRequest, NextResponse } from \"next/server\";\n\nexport async function POST(request: NextRequest) {\n  const { userId } = auth();\n\n  if (!userId)\n    return NextResponse.json({ error: \"Not authorized\" }, { status: 401 });\n\n  let body = await request.json();\n  body = { userId, ...body };\n\n  const validation = favoriteSchema.safeParse(body);\n\n  if (!validation.success)\n    return NextResponse.json(validation.error.format(), { status: 400 });\n\n  const alreadyExists = await prisma.favorite.findFirst({\n    where: {\n      id: body.userId,\n      listingId: body.listingId,\n    },\n  });\n\n  if (alreadyExists) {\n    try {\n      await prisma.favorite.delete({\n        where: {\n          id: alreadyExists.id,\n        },\n      });\n      return NextResponse.json(\n        { success: \"Favorite removed\" },\n        { status: 200 }\n      );\n    } catch (error) {\n      return NextResponse.json(error, { status: 500 });\n    }\n  }\n\n  try {\n    const newFavorite = await prisma.favorite.create({\n      data: {\n        userId: body.userId,\n        listingId: body.listingId,\n      },\n    });\n\n    return NextResponse.json(newFavorite, { status: 201 });\n  } catch (error) {\n    return NextResponse.json(error, { status: 500 });\n  }\n}\n```\n\n```text\nmodel User {\n  id        String     @id @default(cuid())\n  userId    String     @unique\n  favorites Favorite[]\n  reviews   Review[]\n}\n\nmodel Favorite {\n  id String @id @default(cuid())\n\n  clerkId String\n  user    User   @relation(fields: [clerkId], references: [userId])\n\n  listingId String\n  listing   Listing @relation(fields: [listingId], references: [id])\n}\n```\n\n```text\n{\n    \"name\": \"PrismaClientKnownRequestError\",\n    \"code\": \"P2003\",\n    \"clientVersion\": \"5.9.1\",\n    \"meta\": {\n        \"modelName\": \"Favorite\",\n        \"field_name\": \"Favorite_clerkId_fkey (index)\"\n    }\n}\n```\n\n```text\nlistingId\n```\n\n```text\nauth()\n```\n\n========================================\n\nComments:\n- I don't use Prisma, so take this for what is worth. The example here Relations shows the relation `user User` being defined before the relation field `userId String @unique`\n- I love you bro.","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":289,"estimatedTokens":1707}}264{"id":"stack-74505057","source":"stackoverflow","questionId":74505057,"title":"Connecting Prisma to Azure SQL Database","tags":["sql-server","azure","prisma"],"text":"Title: Connecting Prisma to Azure SQL Database\nTags: sql-server, azure, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect Prisma to an SQL Database in Azure. I noticed that my Azure SQL Database connection string does not look anything like the connection strings in the Prisma getting started document.\n\n```\nServer=tcp:mufdatabase.database.windows.net,1433;Initial Catalog=muf;Persist Security Info=False;User ID=muf;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;\n```\n\nWhereas Prisma lists MS SQL Server connection string example as\n\n```\nsqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;\n```\n\nI thought Azure SQL Database was just an SQL Server so why would the connection strings be so different? Does Prisma support Azure SQL Database?\n\n========================================\n\nCode:\n```text\nServer=tcp:mufdatabase.database.windows.net,1433;Initial Catalog=muf;Persist Security Info=False;User ID=muf;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;\n```\n\n```text\nsqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;\n```\n\n```text\nServer=tcp:mufdatabase.database.windows.net,1433;\nInitial Catalog=muf;\nPersist Security Info=False;\nUser ID=muf;\nPassword={your_password};\nMultipleActiveResultSets=False;\nEncrypt=True;\nTrustServerCertificate=False;\nConnection Timeout=30;\n```\n\n```text\nsqlserver://mufdatabase.database.windows.net:1433;\ndatabase=muf;\nuser=muf;\npassword={your_password};\nencrypt=true;\ntrustServerCertificate=false;\nhostNameInCertificate=*.database.windows.net;\nloginTimeout=30;\n```\n\n```text\nprisma\n```\n\n```text\n3.0.1\n```\n\n```text\n2.10.0\n```\n\n```text\nprisma\n```\n\n========================================\n\nComments:\n- Microsoft SQL Server / Azure SQL support was announced as being generally available as part of prisma version 3.0.1 in a blog post on September 07, 2021: prisma.io/blog/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.843Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":73,"estimatedTokens":506}}265{"id":"stack-70985317","source":"stackoverflow","questionId":70985317,"title":"Prisma client not marking property as null","tags":["prisma","prisma2"],"text":"Title: Prisma client not marking property as null\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI am using Prisma version 3.8.1. Prisma client does not mark the User.oauthData property as nullable in TS. Can someone help? Prisma schema and generated SQL files below:\n\n```\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = \"prisma-client-js\"\n binaryTargets = [\"native\", \"rhel-openssl-1.0.x\"]\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel Account {\n id BigInt @id\n createdAt DateTime @db.Timestamptz(3) @default(now())\n updatedAt DateTime @db.Timestamptz(3) @updatedAt\n name String\n users User[]\n}\n\nmodel User {\n id BigInt @id\n createdAt DateTime @db.Timestamptz(3) @default(now())\n updatedAt DateTime @db.Timestamptz(3) @updatedAt\n accountId BigInt\n account Account @relation(fields: [accountId], references: [id])\n fullName String\n email String\n oauthData Json?\n}\n```\n\n```\n-- CreateTable\nCREATE TABLE \"Account\" (\n \"id\" BIGINT NOT NULL,\n \"createdAt\" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \"updatedAt\" TIMESTAMPTZ(3) NOT NULL,\n \"name\" TEXT NOT NULL,\n\n CONSTRAINT \"Account_pkey\" PRIMARY KEY (\"id\")\n);\n\n-- CreateTable\nCREATE TABLE \"User\" (\n \"id\" BIGINT NOT NULL,\n \"createdAt\" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \"updatedAt\" TIMESTAMPTZ(3) NOT NULL,\n \"accountId\" BIGINT NOT NULL,\n \"fullName\" TEXT NOT NULL,\n \"email\" TEXT NOT NULL,\n \"oauthData\" JSONB,\n\n CONSTRAINT \"User_pkey\" PRIMARY KEY (\"id\")\n);\n\n-- AddForeignKey\nALTER TABLE \"User\" ADD CONSTRAINT \"User_accountId_fkey\" FOREIGN KEY (\"accountId\") REFERENCES \"Account\"(\"id\") ON DELETE RESTRICT ON UPDATE CASCADE;\n```\n\nI am using Prisma version 3.8.1. Prisma client does not mark the User.oauthData property as nullable in TS. Can someone help? Prisma schema and generated SQL files below:\n\n========================================\n\nCode:\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n  provider = \"prisma-client-js\"\n  binaryTargets = [\"native\", \"rhel-openssl-1.0.x\"]\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Account {\n  id BigInt @id\n  createdAt DateTime @db.Timestamptz(3) @default(now())\n  updatedAt DateTime @db.Timestamptz(3) @updatedAt\n  name String\n  users User[]\n}\n\nmodel User {\n  id BigInt @id\n  createdAt DateTime @db.Timestamptz(3) @default(now())\n  updatedAt DateTime @db.Timestamptz(3) @updatedAt\n  accountId BigInt\n  account Account @relation(fields: [accountId], references: [id])\n  fullName String\n  email String\n  oauthData Json?\n}\n```\n\n```text\n-- CreateTable\nCREATE TABLE \"Account\" (\n    \"id\" BIGINT NOT NULL,\n    \"createdAt\" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,\n    \"updatedAt\" TIMESTAMPTZ(3) NOT NULL,\n    \"name\" TEXT NOT NULL,\n\n    CONSTRAINT \"Account_pkey\" PRIMARY KEY (\"id\")\n);\n\n-- CreateTable\nCREATE TABLE \"User\" (\n    \"id\" BIGINT NOT NULL,\n    \"createdAt\" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,\n    \"updatedAt\" TIMESTAMPTZ(3) NOT NULL,\n    \"accountId\" BIGINT NOT NULL,\n    \"fullName\" TEXT NOT NULL,\n    \"email\" TEXT NOT NULL,\n    \"oauthData\" JSONB,\n\n    CONSTRAINT \"User_pkey\" PRIMARY KEY (\"id\")\n);\n\n-- AddForeignKey\nALTER TABLE \"User\" ADD CONSTRAINT \"User_accountId_fkey\" FOREIGN KEY (\"accountId\") REFERENCES \"Account\"(\"id\") ON DELETE RESTRICT ON UPDATE CASCADE;\n```\n\n```text\nprisma-script> select id, \"oauthData\" from \"User\"\n+---------+-------------+\n| id      | oauthData   |\n|---------+-------------|\n| 124124  | null        |\n| 1241241 | <null>      |\n+---------+-------------+\n```\n\n```text\nnull\n```\n\n```text\nPrisma.DbNull\n```\n\n```text\nPrisma.JsonNull\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- So how does TS type looks like then? Did you run `prisma generate`?\n- I did run prisma generate. TS type marks it as a non optional\n- Optional and nullable are different things though. Can you just show the type we are talking about? I've tried your schema locally and it works fine, type is nullable as expected.\n- In which file can I find the code for the generated User type? It's marked as non-nullable for sure though based on VS code intellisense popups.\n- Press F12 one something where you can see the popup. Basically it should be in the `node_modules&#47;.prisma&#47;client&#47;index.d.ts`","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":170,"estimatedTokens":1105}}266{"id":"stack-66160753","source":"stackoverflow","questionId":66160753,"title":"Should I run prisma migrate on every app start?","tags":["node.js","docker","kubernetes","prisma"],"text":"Title: Should I run prisma migrate on every app start?\nTags: node.js, docker, kubernetes, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm deploying a Node.js project that uses PostgreSQL with Prisma to Kubernetes. I created the `Dockerfile` and I'm building the docker image to Docker Hub:\n\n```\nFROM node:lts-slim\n\nWORKDIR /app\n\n# Add `/app/node_modules/.bin` to $PATH\nENV PATH /app/node_modules/.bin:$PATH\nENV NODE_ENV=production\n\nRUN apt-get update\n\n# Install Chromium\nRUN apt-get install chromium -y\n\n# Install yarn\nRUN apt-get install yarn -y\n\nCOPY package.json /app/package.json\nRUN yarn install --silent\n\n# Add app\nCOPY . /app\n\n# Generate prisma\nRUN yarn run generate\n\n# Build the app\nRUN yarn build\n\nEXPOSE 4000\n\n# Start the app\nCMD [\"yarn\", \"run\", \"start\"]\n```\n\nI want to use CI/CD, so I would need to check if the PostgreSQL is updated. This can be done with `npx prisma migrate resolve --preview-feature`\n\nI thought on always running the `prisma migrate` to check if the DB is updated, since if a new build changes the `schema`, the DB should reflect it.\n\nSince K8s pods are ephemeral, is it right to add the `npx prisma migrate resolve --preview-feature` to the `start` script, so every time the app starts, it also checks the DB? I don't think running `prisma migrate` all the time is good, but what would be the solution?\n\n========================================\n\nCode:\n```dockerfile\nFROM node:lts-slim\n\nWORKDIR /app\n\n# Add `/app/node_modules/.bin` to $PATH\nENV PATH /app/node_modules/.bin:$PATH\nENV NODE_ENV=production\n\nRUN apt-get update\n\n# Install Chromium\nRUN apt-get install chromium -y\n\n# Install yarn\nRUN apt-get install yarn -y\n\nCOPY package.json /app/package.json\nRUN yarn install --silent\n\n# Add app\nCOPY . /app\n\n# Generate prisma\nRUN yarn run generate\n\n# Build the app\nRUN yarn build\n\nEXPOSE 4000\n\n# Start the app\nCMD [\"yarn\", \"run\", \"start\"]\n```\n\n```text\nDockerfile\n```\n\n```text\nnpx prisma migrate resolve --preview-feature\n```\n\n```text\nprisma migrate\n```\n\n```text\nschema\n```\n\n```text\nnpx prisma migrate resolve --preview-feature\n```\n\n```text\nstart\n```\n\n```text\nprisma migrate\n```\n\n```text\nprisma migrate deploy\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":117,"estimatedTokens":535}}267{"id":"stack-73408381","source":"stackoverflow","questionId":73408381,"title":"Sending Enum Value with spaces using Prisma and MySQL","tags":["mysql","next.js","prisma"],"text":"Title: Sending Enum Value with spaces using Prisma and MySQL\nTags: mysql, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI am going to try my best to explain this issue...\n\nI am working on building a request tracker App in NextJS using Prisma as the ORM and MySQL as the Database.\n\nI am wanting to be able to send the `Status` to the Database without having to add the Underscores into it.\n\nIs this possible?\n\nHere is my Prisma Schema\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n binaryTargets = [\"native\", \"darwin\"]\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel requests {\n id Int @id @default(autoincrement())\n project_id String @db.VarChar(255)\n request_type requests_request_type?\n name String? @db.VarChar(255)\n account_name String? @db.VarChar(255)\n legacy_org requests_legacy_org?\n total_hours_spent Int?\n status requests_status?\n updated_on DateTime? @default(now()) @db.DateTime(0)\n comment String? @db.Text\n}\n\nenum requests_request_type {\n Rem\n Add_on @map(\"Add on\")\n New_Logo @map(\"New Logo\")\n Migration\n}\n\nenum requests_legacy_org {\n CSC\n ES\n}\n\nenum requests_status {\n To_be_Started @map(\"To be Started\")\n Work_in_Progress @map(\"Work in Progress\")\n Awaiting_Customer_Confirmation @map(\"Awaiting Customer Confirmation\")\n Completed\n}\n```\n\nThis function creates the entry in the Database\n\n```\nimport type {NextApiRequest, NextApiResponse} from 'next';\nimport prisma from '../../../../lib/prisma';\n\nexport default async function handle(\n req: NextApiRequest,\n res: NextApiResponse\n) {\n const {name, projectID, accountName, status, requestType, totalHours} =\n req.body;\n const result = await prisma.requests.create({\n data: {\n name: name,\n project_id: projectID,\n account_name: accountName,\n status: status,\n request_type: requestType,\n total_hours_spent: totalHours,\n },\n });\n res.json(result);\n}\n```\n\nThis is my page to add the request\n\n```\nimport React, {useState} from 'react';\nimport Router from 'next/router';\n\nconst AddRequest = () => {\n const [name, setName] = useState('');\n const [projectID, setProjectID] = useState('');\n const [accountName, setAccountName] = useState('');\n const [status, setStatus] = useState('To_be_Started');\n const [requestType, setRequestType] = useState('');\n const [totalHours, setTotalHours] = useState(0);\n\n const submitData = async (e: React.SyntheticEvent) => {\n e.preventDefault();\n try {\n const data = {\n name,\n projectID,\n accountName,\n status,\n requestType,\n totalHours,\n };\n await fetch('/api/requests/add', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify(data),\n });\n await Router.push('/requests');\n } catch (error) {\n console.log(error);\n }\n };\n return (\n <>\n \n \n \n\n### New Request\n\n \n {\n setName(e.target.value);\n }}\n />\n {\n setProjectID(e.target.value);\n }}\n value={projectID}\n />\n {\n setAccountName(e.target.value);\n }}\n value={accountName}\n />\n {\n setRequestType(e.target.value);\n }}\n value={requestType}\n />\n \n Create\n \n \n \n \n \n );\n};\nexport default AddRequest;\n```\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n  binaryTargets = [\"native\", \"darwin\"]\n}\n\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel requests {\n  id                Int                    @id @default(autoincrement())\n  project_id        String                 @db.VarChar(255)\n  request_type      requests_request_type?\n  name              String?                @db.VarChar(255)\n  account_name      String?                @db.VarChar(255)\n  legacy_org        requests_legacy_org?\n  total_hours_spent Int?\n  status            requests_status?\n  updated_on        DateTime?              @default(now()) @db.DateTime(0)\n  comment           String?                @db.Text\n}\n\nenum requests_request_type {\n  Rem\n  Add_on    @map(\"Add on\")\n  New_Logo  @map(\"New Logo\")\n  Migration\n}\n\nenum requests_legacy_org {\n  CSC\n  ES\n}\n\nenum requests_status {\n  To_be_Started                  @map(\"To be Started\")\n  Work_in_Progress               @map(\"Work in Progress\")\n  Awaiting_Customer_Confirmation @map(\"Awaiting Customer Confirmation\")\n  Completed\n}\n```\n\n```js\nimport type {NextApiRequest, NextApiResponse} from 'next';\nimport prisma from '../../../../lib/prisma';\n\nexport default async function handle(\n    req: NextApiRequest,\n    res: NextApiResponse\n) {\n    const {name, projectID, accountName, status, requestType, totalHours} =\n        req.body;\n    const result = await prisma.requests.create({\n        data: {\n            name: name,\n            project_id: projectID,\n            account_name: accountName,\n            status: status,\n            request_type: requestType,\n            total_hours_spent: totalHours,\n        },\n    });\n    res.json(result);\n}\n```\n\n```js\nimport React, {useState} from 'react';\nimport Router from 'next/router';\n\nconst AddRequest = () => {\n    const [name, setName] = useState('');\n    const [projectID, setProjectID] = useState('');\n    const [accountName, setAccountName] = useState('');\n    const [status, setStatus] = useState('To_be_Started');\n    const [requestType, setRequestType] = useState('');\n    const [totalHours, setTotalHours] = useState(0);\n\n    const submitData = async (e: React.SyntheticEvent) => {\n        e.preventDefault();\n        try {\n            const data = {\n                name,\n                projectID,\n                accountName,\n                status,\n                requestType,\n                totalHours,\n            };\n            await fetch('/api/requests/add', {\n                method: 'POST',\n                headers: {'Content-Type': 'application/json'},\n                body: JSON.stringify(data),\n            });\n            await Router.push('/requests');\n        } catch (error) {\n            console.log(error);\n        }\n    };\n    return (\n        <>\n            <div className=\"container flex-auto\">\n                <form onSubmit={submitData}>\n                    <h1 className=\"text-3xl\">New Request</h1>\n                    <div className=\"text-center grid grid-cols-2 gap-3\">\n                        <input\n                            className=\"border border-black\"\n                            type=\"text\"\n                            placeholder=\"Name\"\n                            value={name}\n                            onChange={(e) => {\n                                setName(e.target.value);\n                            }}\n                        />\n                        <input\n                            className=\"border border-black\"\n                            type=\"text\"\n                            placeholder=\"Project ID\"\n                            onChange={(e) => {\n                                setProjectID(e.target.value);\n                            }}\n                            value={projectID}\n                        />\n                        <input\n                            className=\"border border-black\"\n                            type=\"text\"\n                            placeholder=\"Account Name\"\n                            onChange={(e) => {\n                                setAccountName(e.target.value);\n                            }}\n                            value={accountName}\n                        />\n                        <input\n                            className=\"border border-black\"\n                            type=\"text\"\n                            placeholder=\"Request Type\"\n                            onChange={(e) => {\n                                setRequestType(e.target.value);\n                            }}\n                            value={requestType}\n                        />\n                        <button\n                            className=\"border border-black bg-red-100\"\n                            disabled={!name || !projectID}\n                            type=\"submit\">\n                            Create\n                        </button>\n                    </div>\n                </form>\n            </div>\n        </>\n    );\n};\nexport default AddRequest;\n```\n\n```text\nStatus\n```\n\n```text\nenum requests_status {\n  To_be_Started                  @map(\"To be Started\")\n  Work_in_Progress               @map(\"Work in Progress\")\n  Awaiting_Customer_Confirmation @map(\"Awaiting Customer Confirmation\")\n  Completed\n}\n```\n\n```text\nexport const requests_status: {\n  To_be_Started: 'To_be_Started',\n  Work_in_Progress: 'Work_in_Progress',\n  Awaiting_Customer_Confirmation: 'Awaiting_Customer_Confirmation',\n  Completed: 'Completed'\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":342,"estimatedTokens":2132}}268{"id":"stack-73680309","source":"stackoverflow","questionId":73680309,"title":"dynamic sorting in prisma and typed queries","tags":["typescript","orm","prisma"],"text":"Title: dynamic sorting in prisma and typed queries\nTags: typescript, orm, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to define a query in prisma at runtime, but getting stuck at the first hurdle.\n\nso this works:\n\n```\nconst items = await prisma.styleTags.findMany({\n orderBy: {\n name: 'asc',\n }\n });\n```\n\nbut when I try to separately define the query I get TS errors.\n\n```\nconst orderBy = {\n cname: 'asc',\n }\n const items2 = await prisma.styleTags.findMany({\n orderBy\n });\n```\n\nthose two things *should* be identical? but somewhere deep in prisma's maze of automagically generated code...\n\n```\nType '{ cname: string; priority: string; }' is not assignable to type 'Enumerable | undefined'.\n Type '{ cname: string; priority: string; }' is not assignable to type 'StyleTagsOrderByWithRelationInput'.\n Types of property 'cname' are incompatible.\n Type 'string' is not assignable to type 'SortOrder | undefined'.\n```\n\nfrom `Type 'string' is not assignable to type 'SortOrder | undefined'.` I thought maybe I can just pass `orderBy: 'name'` but that fails too.\n\nFWIW if i `@ts-ignore` the code works, but if prisma typechecking has to be ignored, then it serves little purpose.\n\nmy next step after that is to try to dynamically compose the `orderBy` from passed in parameters, but I need to get the basics above to work first.\n\nCan someone suggest why this typechecking of prisma fails?\n\n========================================\n\nTop Answer:\nThis is my NextJs api endpoint logic:\n\n```\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport prisma from '@/lib/prisma';\n\nexport default async function handler(req: NextApiRequest, res: NextApiResponse) {\n const { _page, _limit, _sort, _order} = req.query;\n const limit = +(_limit ?? 20);\n const offset = (+(_page ?? 1) -1 ) * limit;\n const sort = (_sort ?? 'id').toString();\n const order = _order ?? 'asc';\n\n const orderBy = {[sort]: order};\n const userCount = await prisma.users.count();\n const users = await prisma.users.findMany({\n orderBy,\n skip: offset,\n take: limit\n });\n\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('x-total-count', userCount);\n res.status(200).json(users);\n}\n```\n\nI hope it will help\n\n========================================\n\nCode:\n```text\nconst items = await prisma.styleTags.findMany({\n    orderBy: {\n      name: 'asc',\n    }\n  });\n```\n\n```text\nconst orderBy = {\n    cname: 'asc',\n  }\n  const items2 = await prisma.styleTags.findMany({\n    orderBy\n  });\n```\n\n```text\nType '{ cname: string; priority: string; }' is not assignable to type 'Enumerable<StyleTagsOrderByWithRelationInput> | undefined'.\n  Type '{ cname: string; priority: string; }' is not assignable to type 'StyleTagsOrderByWithRelationInput'.\n    Types of property 'cname' are incompatible.\n      Type 'string' is not assignable to type 'SortOrder | undefined'.\n```\n\n```text\nType 'string' is not assignable to type 'SortOrder | undefined'.\n```\n\n```text\norderBy: 'name'\n```\n\n```text\n@ts-ignore\n```\n\n```text\norderBy\n```\n\n```text\norderBy\n```\n\n```text\nas const\n```\n\n```text\ntypescript\n```\n\n```text\nPrisma.orderBy.asc\n```\n\n```text\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport prisma from '@/lib/prisma';\n\nexport default async function handler(req: NextApiRequest, res: NextApiResponse) {\n    const { _page, _limit, _sort, _order} = req.query;\n    const limit = +(_limit ?? 20);\n    const offset = (+(_page ?? 1) -1 ) * limit;\n    const sort = (_sort ?? 'id').toString();\n    const order = _order ?? 'asc';\n\n    const orderBy = {[sort]: order};\n    const userCount = await prisma.users.count();\n    const users = await prisma.users.findMany({\n        orderBy,\n        skip: offset,\n        take: limit\n    });\n\n    res.setHeader('Content-Type', 'application/json');\n    res.setHeader('x-total-count', userCount);\n    res.status(200).json(users);\n}\n```\n\n========================================\n\nComments:\n- This is considering `cname` as string in `orderBy` object when you are creating `orderBy` object separately.\n- `const orderBy = { cname: 'asc', } as const` may help to stop typescript from inferring the `cname` as string","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":166,"estimatedTokens":1031}}269{"id":"stack-71908500","source":"stackoverflow","questionId":71908500,"title":"Prisma: Finding items where two fields have the same value","tags":["prisma"],"text":"Title: Prisma: Finding items where two fields have the same value\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:\n\n```\nselect updated_at,\n cast(sign(sum(case when updated_at = created_at then \n 1 \n else\n 0\n end)) as int) as never_modified\n from tab\n group by updated_at\n```\n\nIs it possible to achieve this in Prisma?\n\n========================================\n\nTop Answer:\nyou can use the preview feature fieldReference of prisma.\n\nschema.prisma\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"fieldReference\"]\n}\n```\n\nyour code\n\n```\nprisma.project.findMany({\n where: { created_at: prisma.project.fields.updated_at }\n})\n```\n\n========================================\n\nCode:\n```sql\nselect updated_at,\n       cast(sign(sum(case when updated_at = created_at then \n          1 \n       else\n          0\n       end)) as int) as never_modified\n  from tab\n group by updated_at\n```\n\n```js\nimport { PrismaClient } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\nasync function initiateDatesComparisonRawQuery() {\n  const response =\n    await prisma.$queryRaw`SELECT * FROM \"public\".\"Project\" WHERE \"created_at\" = \"updated_at\";`;\n\n  console.log(response);\n}\n\nawait initiateDatesComparisonRawQuery();\n```\n\n```text\ngenerator client {\n  provider        = \"prisma-client-js\"\n  previewFeatures = [\"fieldReference\"]\n}\n```\n\n```js\nprisma.project.findMany({\n  where: { created_at: prisma.project.fields.updated_at }\n})\n```\n\n```js\nprisma.project.findMany({\n  where: { \n    created_at: {\n      equals: prisma.project.fields.updated_at\n    }\n  }\n});\n```\n\n```text\nequals\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":463}}270{"id":"stack-68909400","source":"stackoverflow","questionId":68909400,"title":"Prisma model Generation -","tags":["next.js","prisma"],"text":"Title: Prisma model Generation -\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nSorry in advance if question is basic, I am beginner.\n\nIs there a way in the schema.prisma definition to enforce a a column to be the result of an operation on several others column ?\n\ne.g. column 1 = Sum ( column 2 + column 3) ?\n\nAll that in the same table.\nSo that if column 3 is modified, column 1 will automatically be updated as well.\n\nThank you in advance\n\n========================================\n\nCode:\n```text\nmodel Foo {\n  id        Int      @id @default(autoincrement())\n  col1 Int\n  col2 Int\n  colSum Int?  // colSum = col1 + col2\n}\n```\n\n```sql\nCREATE OR REPLACE FUNCTION trigger_col_update()\nRETURNS TRIGGER\nAS $$\nBEGIN\n  NEW.\"colSum\" := NEW.\"col1\" + NEW.\"col2\";\n\nRETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE TRIGGER set_col_trigger\n    BEFORE INSERT OR UPDATE ON \"Foo\"\n                         FOR EACH ROW\n                         EXECUTE PROCEDURE trigger_col_update();\n```\n\n```sh\nnpx prisma migrate dev --create-only\n```\n\n```sh\nnpx prisma migrate dev\n```\n\n```text\ncolSum\n```\n\n```text\nFoo\n```\n\n```text\nFoo\n```\n\n```text\n--create-only\n```\n\n```text\nmigration.sql\n```\n\n```text\ncol1\n```\n\n```text\ncol2\n```\n\n```text\ncolSum\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":84,"estimatedTokens":307}}271{"id":"stack-73369742","source":"stackoverflow","questionId":73369742,"title":"How to differentiate NextAuth user signin and signup?","tags":["next.js","prisma","next-auth"],"text":"Title: How to differentiate NextAuth user signin and signup?\nTags: next.js, prisma, next-auth\nSource: Stack Overflow\n\nQuestion:\nI am building a blog platform using Nextjs 12, NextAuth(Google), Prisma(MySQL). When a user first signs up to my platform, NextAuth automatically saves user's google email address and google name to my database. I want to make user change their nickname when first signing up.\n\nHow would I know if the user is signing up or signing in? Currently in NextAuth, you click `signup()` button and you are good for both signup and signin..\n\n========================================\n\nCode:\n```text\nsignup()\n```\n\n```text\nconst { data: session, status } = useSession()\n\nif(status === \"authenticated\" && session.user.customName === \"\"){ // or whatever your default value for non-defined fields is\n\n// Show your modal or redirect to the page where the user can change his username\n\n// after user enters his new name, make an API call and update it in your DB\n}\n```\n\n```js\n...\ncallbacks: {\n  async signIn({ user, account, profile, email, credentials }) {\n    if (user.customName) {\n      return true\n    } else {\n      // User has no custom name yet, redirect him\n      return '/pathWhereUserCanSetHisName'\n    }\n  }\n}\n...\n```\n\n```text\nexport default async function middleware(request: NextRequest) {\n   const response = NextResponse.next();\n\n   const userCookie = request.cookies.get(YOUR_CUSTOM_COOKIE_NAME) // the cookie name you set for NextAuth's sessionToken\n   if(!userCookie){\n     // user not logged in\n    return NextResponse.redirect('/login')   \n    }\n   \n   const user = yourCustomUserParsingFunction(userCookie) // parsing the JWT contained in the cookie\n   if(user.customName){\n     return response; // user has a custom name, don't intervene\n   }\n\n   // user has no customName, intervene\n   return NextResponse.redirect('/pathWhereUserCanSetHisName');\n}\n```\n\n```text\ncustomName\n```\n\n```text\ncustomName\n```\n\n```text\nuseSession\n```\n\n```text\npages/api/auth/[...nextauth].js\n```\n\n```text\nsessionToken\n```\n\n```text\nmiddleware.ts\n```\n\n========================================\n\nComments:\n- Amazing! I think the second example you provided would fit perfectly for my case! Thanks:)","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":90,"estimatedTokens":551}}272{"id":"stack-71601464","source":"stackoverflow","questionId":71601464,"title":"`Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”","tags":["node.js","svelte","prisma","vite","sveltekit"],"text":"Title: `Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”\nTags: node.js, svelte, prisma, vite, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have the following error message in my browser upon using sveltekit and the command \"`npm run preview`\":\n\n`Uncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”. Relative module specifiers must start with “./”, “../” or “/”.`\n\nIt references a piece of code that was compiled with \"`npm run build`\" in `localhost:3000/_app/start-b07b1607.js`:\n\n`...s-d1fb5791.js\";import\".prisma/client/index-browser\";let Be=\"\",et=\"\";function ...`\n\nI have tried reproducing this error with using older versions of Prisma, the adaptor and Svelte, switching from pnpm to npm, but nothing helps. I have a MWE repository that comes close to reproducing the error but doesn't actually reproduce it at https://github.com/wvhulle/prisma-sveltekit-bug-report.\n\nHow come the Svelte compiler emits “.prisma/client/index-browser” as a module specifier? Is this an error in Prisma, Vite or something else? The dev mode works without problem.\n\nThe question seems to be related, but is about Vue, not about Svelte.\n\nThanks!\n\n========================================\n\nTop Answer:\nYou need to copy prisma generated files as follows (`package.json`):\n\n```\n{\n \"prisma:inline\": \"cp ./node_modules/.prisma/client/*.js ./node_modules/@prisma/client\",\n \"prisma:generate\": \"prisma generate && npm run prisma:inline\"\n}\n```\n\n========================================\n\nCode:\n```text\nnpm run preview\n```\n\n```text\nUncaught TypeError: Error resolving module specifier “.prisma/client/index-browser”. Relative module specifiers must start with “./”, “../” or “/”.\n```\n\n```text\nnpm run build\n```\n\n```text\nlocalhost:3000/_app/start-b07b1607.js\n```\n\n```text\n...s-d1fb5791.js\";import\".prisma/client/index-browser\";let Be=\"\",et=\"\";function ...\n```\n\n```text\nimport { Enum } from '@prisma/client';\n```\n\n```text\n{\n  \"prisma:inline\": \"cp ./node_modules/.prisma/client/*.js ./node_modules/@prisma/client\",\n  \"prisma:generate\": \"prisma generate && npm run prisma:inline\"\n}\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- > \"It references a piece of code that was compiled\" < Your code or prisma's?\n- @ClemensTolboom I don't recognize my own code in the Svelte compiled (built) file, so I assume it is Prisma's?\n- You code exists twice `prisma-client&#47;index-browser.js:1:const prisma = require('.prisma&#47;client&#47;index-browser')` and `prisma-client&#47;scripts&#47;backup-index-browser.js:1:const prisma = require('.prisma&#47;client&#47;index-browser')` Not sure but ... you can try to change those into `require('.&#47;.prisma&#47;client&#47;index-browser')` to check it fixes it? I learned the existance of hidden dirs :-p\n- @ClemensTolboom Maybe i confused you with the repository and you thought something is wrong with the repository. It works in the repository, since I couldn't reproduce the issue. So I am not sure what you mean with the comment.\n- Your code (not the MWE) has a wrong path which you can edit to see if there's a workaround.\n- I think a better solution is: \\ `resolve: { alias: { \".prisma&#47;client&#47;index-browser\": \".&#47;node_modules&#47;.prisma&#47;client&#47;index-browser.js\" } }` \\ from github.com/prisma/prisma/issues/12504#issuecomment-128588308&zwnj;&#8203;3 \\ (if that doesnt work, maybe use `@` instead of `.`, `'.prisma&#47;client&#47;index-browser': '.&#47;node_modules&#47;@prisma&#47;client&#47;index-browser.js',`)","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":80,"estimatedTokens":887}}273{"id":"stack-68520816","source":"stackoverflow","questionId":68520816,"title":"Using prisma and typescript models in parallel","tags":["typescript","prisma"],"text":"Title: Using prisma and typescript models in parallel\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI often use const assertions in my typescript models:\n\n```\nconst ListingVehicleTypes = [\n \"car\",\n \"motorcycle\",\n \"caravan\",\n \"camper_trailer\"\n] as const;\n\ninterface LISTING {\n vehicleType: typeof ListingVehicleTypes[number];\n ...\n}\n```\n\nAs such, `LISTING[\"vehicleType\"]` is correctly inferred as `\"car\" | \"motorcycle\" | \"caravan\" | \"camper_trailer\"`.\n\n**Can I express such restrictions in my `schema.prisma`?** Neither imports nor typescript utils are allowed in `*.prisma` files:\n\n```\nmodel Listing {\n vehicleType typeof ListingVehicleTypes[number] // no-go\n}\n```\n\n**If not, is there a way to \"enrich\" the prisma models with the type-safer typescript models when prisma-powered DB queries are performed?**\n\nI can always cast the query bodies and responses to `any` but is there a cleaner approach?\n\n*For what it's worth, I'm using the `mongodb` provider -- but I don't think the provider plays a role here.*\n\n========================================\n\nCode:\n```js\nconst ListingVehicleTypes = [\n  \"car\",\n  \"motorcycle\",\n  \"caravan\",\n  \"camper_trailer\"\n] as const;\n\ninterface LISTING {\n  vehicleType: typeof ListingVehicleTypes[number];\n  ...\n}\n```\n\n```js\nmodel Listing {\n    vehicleType   typeof ListingVehicleTypes[number]  // no-go\n}\n```\n\n```text\nLISTING[\"vehicleType\"]\n```\n\n```text\n\"car\" | \"motorcycle\" | \"caravan\" | \"camper_trailer\"\n```\n\n```text\nschema.prisma\n```\n\n```text\n*.prisma\n```\n\n```text\nany\n```\n\n```text\nmongodb\n```\n\n```text\nmodel Listing {\n  vehicleType  VehicleType @default(car)\n}\n\nenum VehicleType {\n  car\n  motorcycle\n  caravan\n  camper_trailer\n}\n```\n\n```text\nimport { Listing } from \"@prisma/client\";\n\ntype VehicleTypes = Listing[\"vehicleType\"];\n```\n\n========================================\n\nComments:\n- That's a step in the right direction, thanks! However, `type VehicleTypes` is just that -- a `type`. And I use the const assertions to retain the iterable qualities of arrays outside of my type declarations (esp. when generating the frontend or when validating via a yup schema). In other words, I cannot iterate prisma-generated types -- `Object.keys(Listing['vehicleType'])` of course throws `'Listing' only refers to a type, but is being used as a value here.` I suppose that's where the link between prisma and ts models ends.\n- If you need to obtain iterable array from a type ts-transformer-keys might help. I haven't used this though, so not sure what the limitations are.","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":108,"estimatedTokens":629}}274{"id":"stack-53798509","source":"stackoverflow","questionId":53798509,"title":"Prisma data modeling has many and belongs to","tags":["graphql","prisma","plumatic-schema"],"text":"Title: Prisma data modeling has many and belongs to\nTags: graphql, prisma, plumatic-schema\nSource: Stack Overflow\n\nQuestion:\nI have a prisma data model that consists of a root Category and a Subcategory. A Category has many Subcategories and a Subcategory belongs to one Category. My model looks like this:\n\n```\ntype Category {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n name: String!\n subCategories: [SubCategory!]! @relation(name: \"Subcategories\")\n }\n\n type SubCategory {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n name: String!\n category: Category! @relation(name: \"ParentCategory\")\n\n cards: [Card!]! @relation(name: \"SubCategoryCards\") #Category @relation(name: \"CardCategory\")\n }\n```\n\nNow when i go to create a new subcategory and via \n\n```\nmutation {\n createSubCategory(data:{\n name:\"This is a test\"\n category:{\n connect:{\n id:\"cjp4tyy8z01a6093756xxb04i\"\n }\n }\n }){\n id\n category{\n name\n id\n }\n }\n}\n```\n\nThis appears to work fine. Below I query for the subcategories and their parent Category and I get the results that I expect.\n\n```\n{\n subCategories{\n id\n name\n category{\n id\n name\n }\n }\n}\n```\n\nHowever, when i try to query a category, and get all of it's sub categories I'm getting an empty array:\n\n```\n{\n categories{\n id\n name\n subCategories{\n id\n name\n }\n }\n}\n```\n\nHow can I query all categories and get their sub categories?\n\n========================================\n\nCode:\n```text\ntype Category {\n    id: ID! @unique\n    createdAt: DateTime!\n    updatedAt: DateTime!\n    name: String!\n    subCategories: [SubCategory!]! @relation(name: \"Subcategories\")\n  }\n\n  type SubCategory {\n    id: ID! @unique\n    createdAt: DateTime!\n    updatedAt: DateTime!\n    name: String!\n    category: Category! @relation(name: \"ParentCategory\")\n\n    cards: [Card!]! @relation(name: \"SubCategoryCards\") #Category @relation(name: \"CardCategory\")\n  }\n```\n\n```text\nmutation {\n    createSubCategory(data:{\n        name:\"This is a test\"\n        category:{\n            connect:{\n                id:\"cjp4tyy8z01a6093756xxb04i\"\n            }\n        }\n    }){\n        id\n        category{\n            name\n            id\n        }\n    }\n}\n```\n\n```text\n{\n    subCategories{\n        id\n        name\n        category{\n            id\n            name\n        }\n    }\n}\n```\n\n```text\n{\n    categories{\n        id\n        name\n        subCategories{\n            id\n            name\n        }\n    }\n}\n```\n\n```text\ntype User {\n  postsWritten: [Post!]!\n  postsLiked: [Post!]!\n}\n\ntype Post {\n  author: User!\n  likes: [User!]!\n}\n```\n\n```text\ntype User {\n  postsWritten: [Post!]! @relation(name: \"AuthorPosts\")\n  postsLiked: [Post!]! @relation(name: \"UserLikes\")\n}\n\ntype Post {\n  author: User! @relation(name: \"AuthorPosts\")\n  likes: [User!]! @relation(name: \"UserLikes\")\n}\n```\n\n```text\n@relation\n```\n\n```text\npostsWritten\n```\n\n```text\npostsLiked\n```\n\n```text\nauthor\n```\n\n```text\nlikes\n```\n\n```text\n@relation\n```\n\n```text\npostsWritten\n```\n\n```text\nauthor\n```\n\n```text\npostsLiked\n```\n\n```text\nlikes\n```\n\n========================================\n\nComments:\n- For Prisma 2.0: prisma.io/docs/reference/tools-and-interfaces/prisma-schema/&zwnj;&#8203;&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":216,"estimatedTokens":791}}275{"id":"stack-77131375","source":"stackoverflow","questionId":77131375,"title":"How to Allow null or Empty String in class-validator for Specific Fields?","tags":["postgresql","nestjs","prisma","dto","class-validator"],"text":"Title: How to Allow null or Empty String in class-validator for Specific Fields?\nTags: postgresql, nestjs, prisma, dto, class-validator\nSource: Stack Overflow\n\nQuestion:\nI'm using class-validator in my NestJS application and have a challenge with certain fields. For instance, I have a field sample_result which can contain a number, but I'd like to be able to update or set this field to null or an empty string ('') under certain circumstances (e.g., if I want to remove the value from the database). The same applies for another field sample_comment which is a string.\n\nHere's the relevant code:\n\n```\n@ApiProperty({ required: false })\n @IsNumber()\n @IsOptional()\n sample_result?: number;\n\n @ApiProperty({ required: false })\n @IsString()\n @IsOptional()\n sample_comment?: string;\n```\n\nThe challenge is that when I send a null or '' for sample_result or sample_comment, I receive a validation error. What's the correct approach or configuration with class-validator to allow null or an empty string for these specific fields while ensuring that when values are provided, they adhere to their respective validations (i.e., number for sample_result and string for sample_comment)?\n\nAny guidance or suggestions would be greatly appreciated. Thanks!\n\nmust be a string\nmust be a number conforming to the specified constraints\n\n========================================\n\nTop Answer:\nYou can set the nullable to true, like below;\n\n```\n@ApiProperty({ required: false, nullable: true })\n @IsNumber()\n @IsOptional()\n sample_result?: number;\n\n @ApiProperty({ required: false, nullable: true })\n @IsString()\n @IsOptional()\n sample_comment?: string;\n```\n\n========================================\n\nCode:\n```text\n@ApiProperty({ required: false })\n  @IsNumber()\n  @IsOptional()\n  sample_result?: number;\n\n  @ApiProperty({ required: false })\n  @IsString()\n  @IsOptional()\n  sample_comment?: string;\n```\n\n```text\nimport { ApiProperty } from '@nestjs/swagger';\nimport { IsNumber, IsString, IsOptional, ValidateIf } from 'class-validator';\n\nexport class YourDto {\n  @ApiProperty({ required: false })\n  @IsNumber()\n  @ValidateIf((obj) => obj.sample_result !== null && obj.sample_result !== '')\n  sample_result?: number | null;\n\n  @ApiProperty({ required: false })\n  @IsString()\n  @ValidateIf((obj) => obj.sample_comment !== null && obj.sample_comment !== '')\n  sample_comment?: string | null;\n}\n```\n\n```text\n@ApiProperty({ required: false, nullable: true })\n  @IsNumber()\n  @IsOptional()\n  sample_result?: number;\n\n  @ApiProperty({ required: false, nullable: true })\n  @IsString()\n  @IsOptional()\n  sample_comment?: string;\n```\n\n========================================\n\nComments:\n- Thank u it still throws an error like: ``` \"isNumber\": \"sample_result must be a number conforming to the specified constraints\" ```\n- That didn't work, unfortunatelly","metadata":{"transformedAt":"2026-08-18T18:33:14.844Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":94,"estimatedTokens":707}}276{"id":"stack-76406012","source":"stackoverflow","questionId":76406012,"title":"Create a record while selecting data from different table in prisma and both have the same relation to the parent table","tags":["node.js","postgresql","asynchronous","database-design","prisma"],"text":"Title: Create a record while selecting data from different table in prisma and both have the same relation to the parent table\nTags: node.js, postgresql, asynchronous, database-design, prisma\nSource: Stack Overflow\n\nQuestion:\nThese are the table\n\n```\nmodel wallet {\n id Int @id @default(autoincrement())\n userId Int @unique\n balance Int @default(0)\n joining_bonus Int @default(0)\n referral_bonus Int @default(0)\n incentive Int @default(0)\n user user @relation(fields: [userId], references: [id])\n}\n\nmodel transaction {\n id Int @id @default(autoincrement())\n userId Int\n type String\n amount Int\n curBalance Int\n payment_gateway String\n payment_id String\n status transaction_status @default(PENDING)\n timestamp DateTime @default(now())\n user user @relation(fields: [userId], references: [id])\n \n}\n```\n\nand i want to execute this query\n\n```\nconst transaction = await prisma.transaction.create({\n data: {\n amount: amount,\n type: type,\n payment_gateway: payment_gateway,\n payment_id: payment_id,\n curBalance: {\n //get data from wallet table and select balance field\n },\n user: {\n connect: {\n id: parseInt(req.user.id)\n }\n }\n \n }\n});\n```\n\nI want to get the data from wallet table while creating the of the transaction record because if i did this in different queries there can be time difference due to async calls and i can get different value of current Balance.\n\nIf this query is possible tell me how or if not how to do this so i can always the latest data.\n\n========================================\n\nCode:\n```text\nmodel wallet {\n  id             Int  @id @default(autoincrement())\n  userId         Int  @unique\n  balance        Int  @default(0)\n  joining_bonus  Int  @default(0)\n  referral_bonus Int  @default(0)\n  incentive      Int  @default(0)\n  user           user @relation(fields: [userId], references: [id])\n}\n\nmodel transaction {\n  id               Int                @id @default(autoincrement())\n  userId           Int\n  type             String\n  amount           Int\n  curBalance       Int\n  payment_gateway String\n  payment_id      String\n  status           transaction_status @default(PENDING)\n  timestamp        DateTime           @default(now())\n  user             user               @relation(fields: [userId], references: [id])\n \n}\n```\n\n```text\nconst transaction = await prisma.transaction.create({\n    data: {\n        amount: amount,\n        type: type,\n        payment_gateway: payment_gateway,\n        payment_id: payment_id,\n        curBalance: {\n            //get data from wallet table and select balance field\n        },\n        user: {\n            connect: {\n                id: parseInt(req.user.id)\n            }\n        }\n        \n    }\n});\n```\n\n```js\nconst userId = parseInt(req.user.id);\n\n// Start a transaction\nconst result = await prisma.$transaction(async (prisma) => {\n  // Lock the row\n  const wallet = await prisma.$queryRaw`SELECT * FROM \"wallet\" WHERE \"userId\" = ${userId} FOR UPDATE`;\n\n  // Perform your updates...\n  const transaction = await prisma.transaction.create({\n    data: {\n      amount: amount,\n      type: type,\n      payment_gateway: payment_gateway,\n      payment_id: payment_id,\n      curBalance: wallet.balance,\n      user: {\n        connect: {\n          id: userId,\n        },\n      },\n    },\n  });\n\n  // Return the results\n  return transaction;\n});\n```\n\n```text\nSELECT FOR UPDATE\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":140,"estimatedTokens":835}}277{"id":"stack-50128413","source":"stackoverflow","questionId":50128413,"title":"Which database server prisma based on?","tags":["graphql","prisma"],"text":"Title: Which database server prisma based on?\nTags: graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI would like to know about Prisma more detail.\n\nFirst of all, I would like to know what database Prisma based on.\n\nIs it RDBMS or Nosql?\n\nAlso, this command create new database server:\n\n```\nprima deploy\n```\n\nI would like to now if this database is based on RDBMS, or NoSql.\n\nAnd how can I access to this database without graphql, such as phpmyadmin or mongobooster?\n\n========================================\n\nCode:\n```text\nprima deploy\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma deploy\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":35,"estimatedTokens":149}}278{"id":"stack-67065859","source":"stackoverflow","questionId":67065859,"title":"Modeling a rating system in Prisma","tags":["next.js","prisma"],"text":"Title: Modeling a rating system in Prisma\nTags: next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to include a rating system (like **YouTube** has it) in my project (using Next.js). How should I model the rating in `Prisma`-language?\n\nI know this is a short question. It deserves a short answer.\n\nThanks, guys!\n\n========================================\n\nCode:\n```text\nPrisma\n```\n\n```text\nmodel User {\n  id           Int       @id @default(autoincrement())\n  email        String    @unique\n  city         String\n  name         String?\n  ratingsGiven Ratings[]\n}\n\nmodel Movie {\n  id      Int       @id @default(autoincrement())\n  name    String    @unique\n  year    DateTime\n  Ratings Ratings[]\n}\n\nmodel Ratings {\n  id      Int     @id @default(autoincrement())\n  rating  Decimal\n  movie   Movie   @relation(fields: [movieId], references: [id])\n  movieId Int\n  user    User    @relation(fields: [userId], references: [id])\n  userId  Int\n}\n```\n\n```text\nmodel Movie {\n  id      Int       @id @default(autoincrement())\n  name    String    @unique\n  year    DateTime\n  thumbsUp Int\n  thumbsDown Int\n}\n```\n\n```text\nconst updatedMovie = await prisma.movie.update({\n  where: { id: 10 }\n  data: {\n    thumbsUp: {\n      increment: 1,\n    },\n  },\n})\n```\n\n```text\nMovie\n```\n\n========================================\n\nComments:\n- Can you describe the context in which you need the rating?","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":73,"estimatedTokens":346}}279{"id":"stack-76696991","source":"stackoverflow","questionId":76696991,"title":"How to fix Prisma 'change would violate the required relation'","tags":["typescript","prisma"],"text":"Title: How to fix Prisma 'change would violate the required relation'\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI am having some trouble with prisma. Apparently there's something wrong with my current schema. After adding one instance of a `PublicKey`, I am unable to add another. I get this error:\n\n```\nPrismaClientKnownRequestError: \nInvalid `prisma.publicKey.create()` invocation:\n\nThe change you are trying to make would violate the required relation 'PublicKeyToUser' between the `PublicKey` and `User` models.\n\n{\n code: 'P2014',\n clientVersion: '5.0.0',\n meta: {\n relation_name: 'PublicKeyToUser',\n model_a_name: 'PublicKey',\n model_b_name: 'User'\n }\n}\n```\n\nThis is my current schema:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nenum Role {\n ADMIN\n USER\n}\n\nmodel PublicKey {\n id String @id @default(uuid())\n key String @unique\n ownerId String @unique\n owner User @relation(fields: [ownerId], references: [id])\n deletedAt DateTime?\n keyActivities KeyActivity[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel User{\n id String @id\n role Role\n publicKey PublicKey?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\nThis is the calling function (`createPublicKeyAndDeleteOld`):\n\n```\nexport async function createPublicKey(data: CreateKeyData) {\n const { ownerId, key } = data;\n\n const response = await db.publicKey.create({\n data: {\n key,\n owner: {\n connect: { id: ownerId },\n },\n },\n });\n\n return response;\n}\n\nexport async function createPublicKeyAndDeleteOld(data: CreateKeyData) {\n const activePublicKey = await getActivePublicKey(data.ownerId);\n\n if (activePublicKey) {\n await db.$transaction([\n db.publicKey.create({\n data: {\n key: data.key,\n owner: {\n connect: { id: data.ownerId },\n },\n },\n }),\n db.publicKey.update({\n where: {\n id: activePublicKey.id,\n },\n data: {\n deletedAt: new Date(),\n },\n }),\n ]);\n } else {\n const response = await createPublicKey(data);\n return response;\n }\n}\n```\n\nAny idea, what I am doing wrong here?\n\n========================================\n\nTop Answer:\nAdd the following sentence next to the foreign key:\n\n```\n- onDelete: Cascade\n```\n\nExample:\n\n```\nModel Post {\nuser User @relation(fields: [user_id], references: [id], onDelete: Cascade)\n}\n```\n\n========================================\n\nCode:\n```bash\nPrismaClientKnownRequestError: \nInvalid `prisma.publicKey.create()` invocation:\n\n\nThe change you are trying to make would violate the required relation 'PublicKeyToUser' between the `PublicKey` and `User` models.\n\n{\n  code: 'P2014',\n  clientVersion: '5.0.0',\n  meta: {\n    relation_name: 'PublicKeyToUser',\n    model_a_name: 'PublicKey',\n    model_b_name: 'User'\n  }\n}\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nenum Role {\n  ADMIN\n  USER\n}\n\nmodel PublicKey {\n  id String @id @default(uuid())\n  key String @unique\n  ownerId String @unique\n  owner User @relation(fields: [ownerId], references: [id])\n  deletedAt DateTime?\n  keyActivities KeyActivity[]\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n}\n\nmodel User{\n  id String @id\n  role Role\n  publicKey PublicKey?\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n}\n```\n\n```text\nexport async function createPublicKey(data: CreateKeyData) {\n  const { ownerId, key } = data;\n\n  const response = await db.publicKey.create({\n    data: {\n      key,\n      owner: {\n        connect: { id: ownerId },\n      },\n    },\n  });\n\n  return response;\n}\n\nexport async function createPublicKeyAndDeleteOld(data: CreateKeyData) {\n  const activePublicKey = await getActivePublicKey(data.ownerId);\n\n  if (activePublicKey) {\n    await db.$transaction([\n      db.publicKey.create({\n        data: {\n          key: data.key,\n          owner: {\n            connect: { id: data.ownerId },\n          },\n        },\n      }),\n      db.publicKey.update({\n        where: {\n          id: activePublicKey.id,\n        },\n        data: {\n          deletedAt: new Date(),\n        },\n      }),\n    ]);\n  } else {\n    const response = await createPublicKey(data);\n    return response;\n  }\n}\n```\n\n```text\nPublicKey\n```\n\n```text\ncreatePublicKeyAndDeleteOld\n```\n\n```text\n- onDelete: Cascade\n```\n\n```text\nModel Post {\nuser User @relation(fields: [user_id], references: [id], onDelete: Cascade)\n}\n```\n\n========================================\n\nComments:\n- This fixed it. I had to also change `publicKey` field to `publicKeys PublicKey[]`\n- This make the relation from one-to-one to one-to-many.","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":251,"estimatedTokens":1159}}280{"id":"stack-76039882","source":"stackoverflow","questionId":76039882,"title":"Pothos GraphQL error: PothosSchemaError: Ref Query has not been implemented","tags":["graphql","prisma","graphql-yoga"],"text":"Title: Pothos GraphQL error: PothosSchemaError: Ref Query has not been implemented\nTags: graphql, prisma, graphql-yoga\nSource: Stack Overflow\n\nQuestion:\nI'm using Pothos GraphQL to create the schema and queries for my graphQL API. I'm using Prisma as the ORM and `@pothos/plugin-prisma` as the plugin.\nWhen I start the `graphql-yoga` server, I get the error below.\n\n```\nfile:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:391\n }\n ^\nPothosSchemaError: Ref Query has not been implemented\n at ConfigStore.onTypeConfig (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:391:6)\n at cb (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:474:3)\n at pendingActions (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:446:32)\n at Array.forEach ()\n at ConfigStore.typeConfigs [as prepareForBuild] (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:446:12)\n at BuildCache.builtTypes [as buildAll] (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/build-cache.ts:172:22)\n at SchemaBuilder.toSchema (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/builder.ts:597:11)\n at file:///C:/Users/user/Documents/Projects/project1/server/schema.ts:5:31\n at ModuleJob.run (node:internal/modules/esm/module_job:194:25)\n[nodemon] app crashed - waiting for file changes before starting...\n```\n\nThis is `builder.ts`:\n\n```\nimport PrismaPlugin from \"@pothos/plugin-prisma\";\nimport type PrismaTypes from '@pothos/plugin-prisma/generated';\nimport { prisma } from \"./db.js\";\nimport SchemaBuilder from \"@pothos/core\";\nimport {DateResolver} from \"graphql-scalars\";\n\nexport const builder = new SchemaBuilder({\n plugins: [PrismaPlugin],\n prisma: {\n client: prisma,\n },\n});\n\nbuilder.addScalarType(\"Date\",DateResolver,{});\n```\n\nThe `schema.ts` just imports the builder object and the two graphQL models:\n\n```\nimport { builder } from \"./builder.js\";\nimport \"./models/Job.js\";\nimport \"./models/JobCostCode.js\";\n\nexport const schema = builder.toSchema({});\n```\n\n`index.ts` creates and starts the server:\n\n```\nimport { createYoga } from 'graphql-yoga'\nimport { createServer } from 'node:http'\nimport { schema } from \"./schema.js\";\n\nconst yoga = createYoga({ schema });\n\nconst server = createServer(yoga);\n\nserver.listen(4000, () => {\n console.log(' 🚀 Server is running on http://localhost:4000');\n});\n```\n\nI tried looking at the Pothos GraphQL Docs but would not find anything. Any help would be appreciated.\n\n========================================\n\nCode:\n```text\nfile:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:391\n    }\n     ^\nPothosSchemaError: Ref Query has not been implemented\n    at ConfigStore.onTypeConfig (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:391:6)\n    at cb (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:474:3)\n    at pendingActions (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:446:32)\n    at Array.forEach (<anonymous>)\n    at ConfigStore.typeConfigs [as prepareForBuild] (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/config-store.ts:446:12)\n    at BuildCache.builtTypes [as buildAll] (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/build-cache.ts:172:22)\n    at SchemaBuilder.toSchema (file:///C:/Users/user/Documents/Projects/project1/node_modules/@pothos/core/src/builder.ts:597:11)\n    at file:///C:/Users/user/Documents/Projects/project1/server/schema.ts:5:31\n    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)\n[nodemon] app crashed - waiting for file changes before starting...\n```\n\n```ts\nimport PrismaPlugin from \"@pothos/plugin-prisma\";\nimport type PrismaTypes from '@pothos/plugin-prisma/generated';\nimport { prisma } from \"./db.js\";\nimport SchemaBuilder from \"@pothos/core\";\nimport {DateResolver} from \"graphql-scalars\";\n\nexport const builder = new SchemaBuilder<{\n    Scalars: {\n        Date: { Input: Date; Output: Date };\n    };\n    PrismaTypes: PrismaTypes;\n}>({\n    plugins: [PrismaPlugin],\n    prisma: {\n        client: prisma,\n    },\n});\n\nbuilder.addScalarType(\"Date\",DateResolver,{});\n```\n\n```ts\nimport { builder } from \"./builder.js\";\nimport \"./models/Job.js\";\nimport \"./models/JobCostCode.js\";\n\nexport const schema = builder.toSchema({});\n```\n\n```ts\nimport { createYoga } from 'graphql-yoga'\nimport { createServer } from 'node:http'\nimport { schema } from \"./schema.js\";\n\nconst yoga = createYoga({ schema });\n\nconst server = createServer(yoga);\n\nserver.listen(4000, () => {\n    console.log(' 🚀 Server is running on http://localhost:4000');\n});\n```\n\n```text\n@pothos/plugin-prisma\n```\n\n```text\ngraphql-yoga\n```\n\n```text\nbuilder.ts\n```\n\n```text\nschema.ts\n```\n\n```text\nindex.ts\n```\n\n```text\nbuilder.queryType({\n  description: 'The query root type.',\n});\n```\n\n```text\nbuilder.queryType({\n  description: 'The query root type.',\n  fields: t => ({\n    helloWorld: t.field({ resolve: () => \"Hello World\" }),\n  }),\n});\n\n// Or somewhere else\n\nbuilder.queryField('helloWorld', t => t.field({\n  resolve: () => \"Hello World\",\n}));\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":176,"estimatedTokens":1350}}281{"id":"stack-71228292","source":"stackoverflow","questionId":71228292,"title":"Generate KeyStone.js 6 schema from modified Prisma schema","tags":["node.js","content-management-system","prisma","keystonejs","keystonejs6"],"text":"Title: Generate KeyStone.js 6 schema from modified Prisma schema\nTags: node.js, content-management-system, prisma, keystonejs, keystonejs6\nSource: Stack Overflow\n\nQuestion:\nI had a project that was using the latest version of Prisma (3.9.1) and was planning to place a CMS on top of it. Keystone seemed like a very good fit as they already use Prisma internally. Unfortunately I couldn't modify the Prisma schema because it was auto-generated from the Keystone schema. Is there a way to reverse the process and get a Keystone schema from Prisma ?\n\n========================================\n\nTop Answer:\nOne option is to paste your Prisma schema into extendedPrismaSchema in keystone/schema.ts as following:\n\n```\nSomeSchema: list({\n fields: {},\n db: {\n extendPrismaSchema() {\n return `\n model YourSchema {\n id String\n name String\n email String\n }\n `;\n }\n }\n })\n```\n\nI don't know how this would affect things, but it's one way!\n\n========================================\n\nCode:\n```text\nSomeSchema: list({\n    fields: {},\n    db: {\n      extendPrismaSchema() {\n        return `\n        model YourSchema {\n          id         String\n          name       String\n          email      String\n        }\n        `;\n      }\n    }\n  })\n```\n\n========================================\n\nComments:\n- I worked on something that at least tries to map the fields from prisma schema to keystone schema. github.com/brookmg/prisma2keystone ...\n- Hey that's cool, thanks for the link","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":56,"estimatedTokens":365}}282{"id":"stack-74891893","source":"stackoverflow","questionId":74891893,"title":"Google Cloud Build, Cloud Run, Cloud SQL Prisma Migration","tags":["node.js","google-cloud-sql","prisma","google-cloud-run","google-cloud-build"],"text":"Title: Google Cloud Build, Cloud Run, Cloud SQL Prisma Migration\nTags: node.js, google-cloud-sql, prisma, google-cloud-run, google-cloud-build\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a Google Cloud Build pipeline running with a Node.js application that is using Google Cloud Build, Cloud SQL (PostgreSQL) and Prisma for the ORM. I have started with the default `yaml` provided by GCP Cloud Build when clicking on the `Setup Continuous Integration` button on the Cloud Run UI view for an existing application. The part that is missing is the prisma migrations for the Cloud SQL instance.\n\n```\nsteps:\n - name: gcr.io/cloud-builders/docker\n args:\n - build\n - '--no-cache'\n - '-t'\n - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n - .\n - '-f'\n - api/Dockerfile\n id: Build\n - name: gcr.io/cloud-builders/docker\n args:\n - push\n - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n id: Push\n - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:slim'\n args:\n - run\n - services\n - update\n - $_SERVICE_NAME\n - '--platform=managed'\n - '--image=$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n - >-\n --labels=managed-by=gcp-cloud-build-deploy-cloud-run,commit-sha=$COMMIT_SHA,gcb-build-id=$BUILD_ID,gcb-trigger-id=$_TRIGGER_ID,$_LABELS\n - '--region=$_DEPLOY_REGION'\n - '--quiet'\n id: Deploy\n entrypoint: gcloud\nimages:\n - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\noptions:\n substitutionOption: ALLOW_LOOSE\ntags:\n - gcp-cloud-build-deploy-cloud-run\n - gcp-cloud-build-deploy-cloud-run-managed\n - api\n```\n\n========================================\n\nCode:\n```yaml\nsteps:\n  - name: gcr.io/cloud-builders/docker\n    args:\n      - build\n      - '--no-cache'\n      - '-t'\n      - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n      - .\n      - '-f'\n      - api/Dockerfile\n    id: Build\n  - name: gcr.io/cloud-builders/docker\n    args:\n      - push\n      - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n    id: Push\n  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:slim'\n    args:\n      - run\n      - services\n      - update\n      - $_SERVICE_NAME\n      - '--platform=managed'\n      - '--image=$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n      - >-\n        --labels=managed-by=gcp-cloud-build-deploy-cloud-run,commit-sha=$COMMIT_SHA,gcb-build-id=$BUILD_ID,gcb-trigger-id=$_TRIGGER_ID,$_LABELS\n      - '--region=$_DEPLOY_REGION'\n      - '--quiet'\n    id: Deploy\n    entrypoint: gcloud\nimages:\n  - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\noptions:\n  substitutionOption: ALLOW_LOOSE\ntags:\n  - gcp-cloud-build-deploy-cloud-run\n  - gcp-cloud-build-deploy-cloud-run-managed\n  - api\n```\n\n```text\nyaml\n```\n\n```text\nSetup Continuous Integration\n```\n\n```yaml\nsteps:\n  - name: 'node:$_NODE_VERSION'\n    entrypoint: 'yarn'\n    id: yarn-install\n    args: ['install']\n    waitFor: [\"-\"]\n\n  - id: migrate\n    name: gcr.io/cloud-builders/yarn\n    env:\n      - NODE_ENV=$_NODE_ENV\n    entrypoint: sh\n    args:\n      - \"-c\"\n      - |\n        wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy\n        chmod +x cloud_sql_proxy\n        ./cloud_sql_proxy -instances=$$_DB_HOST=tcp:$$_DB_PORT & sleep 3\n        export DATABASE_URL=postgresql://$$_DB_USER:$$_DB_PASS@localhost/$$_DB_NAME?schema=public\n        yarn workspace api run migrate\n    secretEnv: ['_DB_USER', '_DB_PASS',  '_DB_HOST', '_DB_NAME', '_DB_PORT']\n    timeout: \"1200s\"\n    waitFor: [\"yarn-install\"]\n\n  - name: gcr.io/cloud-builders/docker\n    args:\n      - build\n      - '--no-cache'\n      - '-t'\n      - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n      - .\n      - '-f'\n      - api/Dockerfile\n    id: Build\n  - name: gcr.io/cloud-builders/docker\n    args:\n      - push\n      - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n    id: Push\n  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:slim'\n    args:\n      - run\n      - services\n      - update\n      - $_SERVICE_NAME\n      - '--platform=managed'\n      - '--image=$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\n      - >-\n        --labels=managed-by=gcp-cloud-build-deploy-cloud-run,commit-sha=$COMMIT_SHA,gcb-build-id=$BUILD_ID,gcb-trigger-id=$_TRIGGER_ID,$_LABELS\n      - '--region=$_DEPLOY_REGION'\n      - '--quiet'\n    id: Deploy\n    entrypoint: gcloud\nimages:\n  - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'\noptions:\n  substitutionOption: ALLOW_LOOSE\navailableSecrets:\n  secretManager:\n  - versionName: projects/$PROJECT_ID/secrets/DB_NAME/versions/latest\n    env: '_DB_NAME'\n  - versionName: projects/$PROJECT_ID/secrets/DB_PASS/versions/latest\n    env: '_DB_PASS'\n  - versionName: projects/$PROJECT_ID/secrets/DB_PORT/versions/latest\n    env: '_DB_PORT'\n  - versionName: projects/$PROJECT_ID/secrets/DB_USER/versions/latest\n    env: '_DB_USER'\n  - versionName: projects/$PROJECT_ID/secrets/DB_HOST/versions/latest\n    env: '_DB_HOST'\n\ntags:\n  - gcp-cloud-build-deploy-cloud-run\n  - gcp-cloud-build-deploy-cloud-run-managed\n  - api\n```\n\n```text\ngit\n```\n\n```text\nRepository\n```\n\n```text\ncloudbuild.yaml\n```\n\n```text\ninline\n```\n\n```text\ncloudbuild.yaml\n```\n\n========================================\n\nComments:\n- Is this cloudbuild in addition to the one on top? Because in this one you're not building, pushing or deploying does this code go below the existing one you put in the question?\n- @JamesDaly I wrote this up awhile ago, but I believe if you scroll down in look at the entire yaml it is `building`, `pushing` and `deploying`. At least the steps named in there are using the gcr.io names that are intended to help with those parts.\n- Why the first step of yarn install? Why is that needed? also why do this in migrate export DATABASE_URL=postgresql://$$_DB_USER:$$_DB_PASS@localhost/$$&zwnj;&#8203;_DB_NAME?schema=publ&zwnj;&#8203;ic yarn workspace api run migrate what does that script do? would that be equivalent of running an npm script\n- Also I posted a similar question - stackoverflow.com/questions/76847376/&hellip;\n- @JamesDaly yes, yarn does a similar job as npm. You can learn about it here yarnpkg.com. As far as that particular migration command, that is a prism database migration script. Primsa is a DB ORM prisma.io\n- thank you again for this answer this helped me on my journey which almost took two weeks to resolve but I finally figured out after implementing this that for my sql on prisma I had to add ?socket=/cloudsql/{connectionname} to my databbase url in cloud run\n- Good to hear it's working for you now!","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":207,"estimatedTokens":1657}}283{"id":"stack-73109066","source":"stackoverflow","questionId":73109066,"title":"Error: Invalid name in Prisma of node.js project","tags":["node.js","npm","prisma"],"text":"Title: Error: Invalid name in Prisma of node.js project\nTags: node.js, npm, prisma\nSource: Stack Overflow\n\nQuestion:\nI used Prisma in a node.js project when I ran the below command\n\n```\nnpx prisma migrate dev\n```\n\nI faced with this error\n\n```\nEnvironment variables loaded from .env\nError: Invalid name: \"project name\"\n```\n\nI don't know what the problem is that printed `Error: Invalid name` when I want to migrate?\n\n========================================\n\nCode:\n```bash\nnpx prisma migrate dev\n```\n\n```text\nEnvironment variables loaded from .env\nError: Invalid name: \"project name\"\n```\n\n```text\nError: Invalid name\n```\n\n```text\n\"name\": \"project-name\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":39,"estimatedTokens":164}}284{"id":"stack-71508948","source":"stackoverflow","questionId":71508948,"title":"Node js search on prisma for string with case insensitivity","tags":["javascript","node.js","prisma"],"text":"Title: Node js search on prisma for string with case insensitivity\nTags: javascript, node.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI want to find the user with a specific email regardless case sensitivity of the email in the DB or in the request body. Using any of the following methods is rendering an undefined function error\n\n```\nconst user = await prisma.User.findUnique({\n where: {\n email: {\n insensitive: {\n equals: req.body.email,\n },\n }\n }\n })\n\n const user = await prisma.User.findUnique({\n where: {\n email: {\n insensitiveEquals: req.body.email\n }\n }\n })\n\n const user = await prisma.User.findUnique({\n where: {\n email: req.body.email,\n mode: 'insensitive'\n }\n })\n```\n\n========================================\n\nTop Answer:\nJust faced something similar in my NextJS application just now. I checked the prisma doc as well, and found the `.findMany` query being used when I actually need to fetch one entity. I had to change the `.findUnique` to `.findFirst` in my own case.\n\nThis is to provide additional guide.\n\n========================================\n\nCode:\n```text\nconst user = await prisma.User.findUnique({\n        where: {\n            email: {\n                insensitive: {\n                    equals: req.body.email,\n                },\n            }\n        }\n    })\n\n    const user = await prisma.User.findUnique({\n        where: {\n            email: {\n                insensitiveEquals: req.body.email\n            }\n        }\n    })\n\n    const user = await prisma.User.findUnique({\n        where: {\n            email: req.body.email,\n            mode: 'insensitive'\n        }\n    })\n```\n\n```text\nconst user = await prisma.user.findMany({\n    where: {\n      email: {\n        equals: 'test@test.com',\n        mode: 'insensitive',\n      },\n    },\n  });\n```\n\n```text\nfindUnique\n```\n\n```text\nuser\n```\n\n```text\nPrismaClient\n```\n\n```text\nnpx prisma generate\n```\n\n```text\nPrismaClient\n```\n\n```text\ninsensitive\n```\n\n```text\n.findMany\n```\n\n```text\n.findUnique\n```\n\n```text\n.findFirst\n```\n\n========================================\n\nComments:\n- Can you what exact error are you getting? Maybe the stack trace? Have you executed `npx prisma generate` to generate Prisma Client? Also can you the user model?","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":122,"estimatedTokens":554}}285{"id":"stack-77966913","source":"stackoverflow","questionId":77966913,"title":"Connecting Google App Engine to a Cloud SQL (Prisma) Postgres instance (through Bitbucket CI/CD)","tags":["google-app-engine","google-cloud-sql","prisma","bitbucket-pipelines"],"text":"Title: Connecting Google App Engine to a Cloud SQL (Prisma) Postgres instance (through Bitbucket CI/CD)\nTags: google-app-engine, google-cloud-sql, prisma, bitbucket-pipelines\nSource: Stack Overflow\n\nQuestion:\nI'm deploying a Google App Engine with a connection to a PostgreSQL CloudSQL instance, managed by Prisma ORM. All this I'm doing through the Bitbucket CI/CD. However I'm experiencing difficulties with setting-up this connection.\n\nThis is the error that I'm bumping into... (I've left out the security sensitive variables). The error occurs in the build step of the Google App Engine deploy image provided by Atlassian here: https://bitbucket.org/atlassian/google-app-engine-deploy/src/master/\n\n```\n> prisma migrate deploy\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma/schema.prisma\nDatasource \"db\": PostgreSQL database \"mydatabasename\", schema \"public\" at \"localhost:5432\"\nError: P1001: Can't reach database server at `/cloudsql/my-project-id:europe-west1:my-instance-name`:`5432`\nPlease make sure your database server is running at /cloudsql/my-project-id:europe-west1:my-instance-name`:`5432``.\n```\n\nI followed the following docs of Google: https://cloud.google.com/sql/docs/postgres/connect-app-engine-standard to connect through a Unix socket, but without luck. Also configured all the necessary IAM Roles.\n\n**Environment:**\n\n```\nDATABASE_URL=\"postgres://username:password@localhost/dbname?host=/cloudsql/my-project-id:region:my-instance-name\"\n```\n\nThis `DATABASE_URL` is injected in schema.prisma like this:\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n```\n\nAnyone that has experience deploying this specific tech stack, and knows how to set-up this connection?\n\n========================================\n\nTop Answer:\nPrisma does support connecting over a Unix socket.\n\nSee https://www.prisma.io/docs/orm/overview/databases/postgresql#connecting-via-sockets.\n\nIt looks like you need to add a trailing slash,e.g.,\n\n```\npostgresql://USER:PASSWORD@localhost/database?host=/cloudsql/my-project-id:region:my-instance-name/\n```\n\n========================================\n\nCode:\n```text\n> prisma migrate deploy\nEnvironment variables loaded from .env\nPrisma schema loaded from prisma/schema.prisma\nDatasource \"db\": PostgreSQL database \"mydatabasename\", schema \"public\" at \"localhost:5432\"\nError: P1001: Can't reach database server at `/cloudsql/my-project-id:europe-west1:my-instance-name`:`5432`\nPlease make sure your database server is running at /cloudsql/my-project-id:europe-west1:my-instance-name`:`5432``.\n```\n\n```text\nDATABASE_URL=\"postgres://username:password@localhost/dbname?host=/cloudsql/my-project-id:region:my-instance-name\"\n```\n\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n```text\nDATABASE_URL\n```\n\n```text\ndefinitions:\n  steps:\n    - step: &prisma-migrate-deploy\n        name: Prisma Migrate Deploy\n        caches:\n          - node\n        script:\n          # Set proxy database url\n          - export DATABASE_URL=$PROXY_DATABASE_URL\n          # Start Cloud SQL Proxy\n          - curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.8.2/cloud-sql-proxy.linux.amd64\n          - chmod +x cloud-sql-proxy\n          - echo $GOOGLE_SERVICE_ACCOUNT | base64 --decode > service-account-key.json\n          - ./cloud-sql-proxy --credentials-file service-account-key.json $CLOUD_SQL_INSTANCE_CONNECTION_NAME & sleep 5\n          # Migrate\n          - npm run migrate:prod\n```\n\n```text\ndatabase_url\n```\n\n```text\nbitbucket-pipelines.yml\n```\n\n```text\npostgresql://USER:PASSWORD@localhost/database?host=/cloudsql/my-project-id:region:my-instance-name/\n```\n\n```text\nbeta_settings:\n  cloud_sql_instances: INSTANCE_CONNECTION_NAME\n```\n\n```text\npostgresql://$POSTGRES_USER:$POSTGRES_PASSWORD@localhost/$POSTGRES_DB_NAME?host=/cloudsql/$INSTANCE_CONNECTION_NAME/\n```\n\n```text\ncloud_sql_instances\n```\n\n```text\nbeta_setting\n```\n\n```text\napp.yaml\n```\n\n```text\nDATABASE_URL\n```\n\n========================================\n\nComments:\n- Can you minimal reproducible steps like how you are connecting using `prisma` and what variables you have in you `.env`(excluding PI), config files etc to replicate. Also have a look at this thread1 & thread2\n- @RoopaM Thank you for reaching out, I've added more context. Currently, I'm trying out this approach github.com/edosrecki/google-cloud-sql-nodejs-connector-examp&zwnj;&#8203;le/&hellip; but without much luck unfortunately.\n- Have you tried changing `DATABASE\\_URL` to `\"postgresql:&#47;&#47;username:password@postgres&#47;dbname?host=&#47;clouds&zwnj;&#8203;ql&#47;my-project-id:reg&zwnj;&#8203;ion:my-instance-name&zwnj;&#8203;\"` or to `\"postgres:&#47;&#47;${DB\\_USER}:${DB\\_PASS}@${DB\\_HOST}:${DB\\_PORT}&#47;&zwnj;&#8203;${DB\\_BASE}?host=${C&zwnj;&#8203;LOUD\\_SQL\\_CONNECTIO&zwnj;&#8203;N\\_NAME}\"` as mentioned in previous link\n- Does this answer your question? stackoverflow.com/q/75294376/11715259","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":140,"estimatedTokens":1247}}286{"id":"stack-53684290","source":"stackoverflow","questionId":53684290,"title":"Prisma generate: Field configuration to merge has duplicate field names","tags":["graphql","prisma","generate","prisma-graphql"],"text":"Title: Prisma generate: Field configuration to merge has duplicate field names\nTags: graphql, prisma, generate, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nRunning *prisma generate* I encurred in this output and no code is generated. \n\n```\nprisma generate\nGenerating schema...\n[ { species: { type: [Object], args: [Object] } },\n { species: { type: [Object], args: [Object] },\nGenerating schema !\n ! Field configuration to merge has duplicate field names.\n```\n\n**What's wrong with my schema?**\n\n```\ntype User {\n id: ID! @unique\n email: String! @unique\n name: String!\n password: String!\n entries: [Entry!]!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Language {\n id: ID! @unique\n language: String! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype EntryScientificName {\n id: ID! @unique\n entry: Entry!\n isMain: Boolean!\n scientificName: String! @unique\n language: Language!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype EntryName {\n id: ID! @unique\n entry: Entry!\n isMain: Boolean!\n name: String! @unique\n Language: Language!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Species {\n id: ID! @unique\n species: String! @unique\n description: String\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Genus {\n id: ID! @unique\n genus: String! @unique\n description: String\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Family {\n id: ID! @unique\n family: String! @unique\n description: String\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Order {\n id: ID! @unique\n order: String! @unique\n description: String\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Habitat {\n id: ID! @unique\n habitat: String! @unique\n description: String\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Month {\n id: ID! @unique\n month: String! @unique\n}\n\ntype Anthesis {\n id: ID! @unique\n entry: Entry\n fromMonth: Month! @relation(name: \"FromMonth\")\n toMonth: Month! @relation(name: \"ToMonth\")\n note: String\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Nation {\n id: ID! @unique\n nation: String! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Region {\n id: ID! @unique\n nation: Nation!\n region: String! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype DistributionDetail {\n id: ID! @unique\n detail: String!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype GeographicDistribution {\n id: ID! @unique\n entry: Entry!\n region: Region!\n detail: DistributionDetail\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n\ntype Altitude {\n id: ID! @unique\n entry: Entry! @unique\n altitudeFrom: Int! @unique @constraint(min: -10894, max: 408000)\n altitudeTo: Int! @unique @constraint(min: -10894, max: 408000)\n}\n\ntype Entry {\n id: ID! @unique\n name: [EntryName!]!\n scientificName: [EntryScientificName!]!\n species: Species\n genus: Genus\n family: Family\n order: Order\n biologicalForm: String\n plantDescription: String\n leafDescription: String\n flowerDescription: String\n fruitDescriptio: String\n chorologicalType: String\n habitat: [Habitat!]!\n geographicDistribution: [GeographicDistribution!]!\n altitude: [Altitude!]!\n etymology: String\n propertiesUses: String\n curiosities: String\n notes: String\n links: [Link!]!\n entryPicture: String\n draft: Boolean @default(value: \"true\")\n published: Boolean @default(value: \"false\")\n toBeReviewed: Boolean @default(value: \"false\")\n createdAt: DateTime!\n updatedAt: DateTime!\n author: User\n}\n\ntype Link {\n id: ID! @unique\n createdAt: DateTime!\n updatedAt: DateTime!\n url: String!\n description: String!\n postedby: User\n}\n```\n\n========================================\n\nCode:\n```text\nprisma generate\nGenerating schema...\n[ { species: { type: [Object], args: [Object] } },\n  { species: { type: [Object], args: [Object] },\nGenerating schema !\n !    Field configuration to merge has duplicate field names.\n```\n\n```text\ntype User {\n  id: ID! @unique\n  email: String! @unique\n  name: String!\n  password: String!\n  entries: [Entry!]!\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Language {\n  id: ID! @unique\n  language: String! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype EntryScientificName {\n  id: ID! @unique\n  entry: Entry!\n  isMain: Boolean!\n  scientificName: String! @unique\n  language: Language!\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype EntryName {\n  id: ID! @unique\n  entry: Entry!\n  isMain: Boolean!\n  name: String! @unique\n  Language: Language!\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Species {\n  id: ID! @unique\n  species: String! @unique\n  description: String\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Genus {\n  id: ID! @unique\n  genus: String! @unique\n  description: String\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Family {\n  id: ID! @unique\n  family: String! @unique\n  description: String\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Order {\n  id: ID! @unique\n  order: String! @unique\n  description: String\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Habitat {\n  id: ID! @unique\n  habitat: String! @unique\n  description: String\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Month {\n  id: ID! @unique\n  month: String! @unique\n}\n\ntype Anthesis {\n  id: ID! @unique\n  entry: Entry\n  fromMonth: Month! @relation(name: \"FromMonth\")\n  toMonth: Month! @relation(name: \"ToMonth\")\n  note: String\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Nation {\n  id: ID! @unique\n  nation: String! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Region {\n  id: ID! @unique\n  nation: Nation!\n  region: String! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype DistributionDetail {\n  id: ID! @unique\n  detail: String!\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype GeographicDistribution {\n  id: ID! @unique\n  entry: Entry!\n  region: Region!\n  detail: DistributionDetail\n  createdAt: DateTime!\n  updatedAt: DateTime!\n}\n\ntype Altitude {\n  id: ID! @unique\n  entry: Entry! @unique\n  altitudeFrom: Int! @unique @constraint(min: -10894, max: 408000)\n  altitudeTo: Int! @unique @constraint(min: -10894, max: 408000)\n}\n\ntype Entry {\n  id: ID! @unique\n  name: [EntryName!]!\n  scientificName: [EntryScientificName!]!\n  species: Species\n  genus: Genus\n  family: Family\n  order: Order\n  biologicalForm: String\n  plantDescription: String\n  leafDescription: String\n  flowerDescription: String\n  fruitDescriptio: String\n  chorologicalType: String\n  habitat: [Habitat!]!\n  geographicDistribution: [GeographicDistribution!]!\n  altitude: [Altitude!]!\n  etymology: String\n  propertiesUses: String\n  curiosities: String\n  notes: String\n  links: [Link!]!\n  entryPicture: String\n  draft: Boolean @default(value: \"true\")\n  published: Boolean @default(value: \"false\")\n  toBeReviewed: Boolean @default(value: \"false\")\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  author: User\n}\n\ntype Link {\n  id: ID! @unique\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  url: String!\n  description: String!\n  postedby: User\n}\n```\n\n```text\nSpecies\n```\n\n```text\nSpecies\n```\n\n```text\nNews\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":385,"estimatedTokens":1740}}287{"id":"stack-76813521","source":"stackoverflow","questionId":76813521,"title":"Invalid value for argument `gte`: input contains invalid characters. Expected ISO-8601 DateTime. (Prisma)","tags":["javascript","sql","prisma"],"text":"Title: Invalid value for argument `gte`: input contains invalid characters. Expected ISO-8601 DateTime. (Prisma)\nTags: javascript, sql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using Prisma with a MySQL database. This is my code:\n\n```\nconst thisYear = Number(\"2023\")\n const newYear = thisYear + 1\n\n const startDate = format(new Date(thisYear, 6, 1), 'yyyy-MM-dd HH:mm:ss')\n const endDate = format(new Date(newYear, 5, 30), 'yyyy-MM-dd HH:mm:ss')\n console.log(\"startDate, endDate: \", startDate, endDate)\n\n const bucketTransactions = await prisma.bucket_transaction.groupBy({\n by: ['bucket_id'],\n _sum: {\n amount: true,\n },\n where: {\n date_added: {\n gte: startDate,\n lte: endDate,\n },\n amount: {\n gt: 0,\n },\n donation_id: {\n gt: 0,\n },\n },\n });\n```\n\nI get this error:\n\n```\nInvalid value for argument `gte`: input contains invalid characters. Expected ISO-8601 DateTime.\n```\n\nThis is the value of startDate and endDate in the console log:\n\n```\nstartDate, endDate: 2023-07-01 00:00:00 2024-06-30 00:00:00\n```\n\nDo you know what's wrong with my code?\n\nI ran this directly into the SQL terminal and it worked:\n\n```\nselect * from bucket_transaction WHERE date_added BETWEEN \"2023-07-01 00:00:00\" and \"2024-06-30 00:00:00\" AND amount > 0 AND donation_id > 0;\n```\n\nWhy doesn't it work with Prisma?\n\n========================================\n\nTop Answer:\nI had to change the startDate and the endDate into a new Date object like this:\n\n```\nwhere: {\n date_added: {\n gte: new Date(startDate),\n lte: new Date(endDate),\n }\n },\n```\n\n========================================\n\nCode:\n```text\nconst thisYear = Number(\"2023\")\n  const newYear = thisYear + 1\n\n  const startDate = format(new Date(thisYear, 6, 1), 'yyyy-MM-dd HH:mm:ss')\n  const endDate = format(new Date(newYear, 5, 30), 'yyyy-MM-dd HH:mm:ss')\n  console.log(\"startDate, endDate: \", startDate, endDate)\n\n  const bucketTransactions = await prisma.bucket_transaction.groupBy({\n       by: ['bucket_id'],\n       _sum: {\n           amount: true,\n       },\n       where: {\n           date_added: {\n               gte: startDate,\n               lte: endDate,\n           },\n           amount: {\n               gt: 0,\n           },\n           donation_id: {\n               gt: 0,\n           },\n       },\n   });\n```\n\n```text\nInvalid value for argument `gte`: input contains invalid characters. Expected ISO-8601 DateTime.\n```\n\n```text\nstartDate, endDate:  2023-07-01 00:00:00 2024-06-30 00:00:00\n```\n\n```text\nselect * from bucket_transaction WHERE date_added BETWEEN \"2023-07-01 00:00:00\" and \"2024-06-30 00:00:00\" AND amount > 0 AND donation_id > 0;\n```\n\n```text\nconst startDate = format(new Date(thisYear, 6, 1), 'yyyy-MM-dd HH:mm:ss')\n```\n\n```text\nconst startDate = new Date(thisYear, 6, 1)\n```\n\n```text\nconst startDate = new Date(thisYear, 6, 1).toISOString()\n```\n\n```text\nwhere: {\n           date_added: {\n               gte: new Date(startDate),\n               lte: new Date(endDate),\n           }\n       },\n```\n\n========================================\n\nComments:\n- Doesn't ISO-8601 require a `T` in the timestamp nowadays? Like `'2023-07-01T00:00:00'`.","metadata":{"transformedAt":"2026-08-18T18:33:14.845Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":139,"estimatedTokens":774}}288{"id":"stack-76361624","source":"stackoverflow","questionId":76361624,"title":"Error: ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY - Broken lockfile in pnpm installation","tags":["next.js","prisma","dependency-management","next-auth","pnpm"],"text":"Title: Error: ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY - Broken lockfile in pnpm installation\nTags: next.js, prisma, dependency-management, next-auth, pnpm\nSource: Stack Overflow\n\nQuestion:\nTitle: Error: ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY - Broken lockfile in pnpm installation\n\nI am encountering an error while trying to run the pnpm install command in my project. The specific error message I'm getting is \"ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY - Broken lockfile: no entry for '/@next-auth/prisma-adapter/1.0.6(@prisma/client@4.14.1)(next-auth@4.22.1)' in pnpm-lock.yaml\".\n\nI have followed the suggested solution of running pnpm install --no-frozen-lockfile, but the error persists. Additionally, I have cleared the cache using pnpm cache clear --force and deleted the pnpm-lock.yaml file before reinstalling the dependencies, but the issue remains unresolved.\n\nI suspect that there might be a deeper issue with my project's configuration or dependencies that is causing this error. I have double-checked the documentation for any troubleshooting guidance, but haven't found a solution specific to this error. The error message mentions a possible merge conflict in the lockfile, but I have resolved any known conflicts and ensured the lockfile is in a valid state.\n\n========================================\n\nTop Answer:\ndeleting the build folder and rebuilding the application worked for me.\n\n========================================\n\nComments:\n- Having the same problem on a Vercel build, but can't reproduce it in local\n- The problem is related with pnpm latest version. More information: github.com/pnpm/pnpm/issues/6609\n- why this error happen?\n- I uninstalled the pnpm completely and reinstall the latest version and it worked somehow.","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":25,"estimatedTokens":435}}289{"id":"stack-54056020","source":"stackoverflow","questionId":54056020,"title":"Q: Intellisense when using context.prisma","tags":["graphql","intellisense","javascript-intellisense","prisma","prisma-graphql"],"text":"Title: Q: Intellisense when using context.prisma\nTags: graphql, intellisense, javascript-intellisense, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm creating my graphql layer with prisma. I have a question about using prisma with typescript in the resolvers.\n\nIn the documentation it is suggested to import prisma to get intellisense:\n\n```\nimport { prisma } from '../generated/prisma-client'\n```\n\nIf you do so, when you are writing a resolver like this one, you won't get any suggestions.\n\n```\nconst user = (parent, args, context, info) => context.prisma.bodyweight({id: parent.id}).user()\n```\n\nTo get the suggestions you would have to write it without referencing the context adding the reference later, which predisposes you to forget it and create bugs.\n\nIs there a way to fix it (maybe in the tsconfig)?\n\n========================================\n\nCode:\n```text\nimport { prisma } from '../generated/prisma-client'\n```\n\n```text\nconst user = (parent, args, context, info) => context.prisma.bodyweight({id: parent.id}).user()\n```\n\n```text\nimport { Prisma } from '../generated/prisma-client';\nexport interface Context{\n  prisma: Prisma;\n}\n\nconst user = (parent, args, context: Context, info) => context.prisma.bodyweight({id: parent.id}).user()\n```\n\n========================================\n\nComments:\n- Hey @DanielMateosLabrador, can you please accept the answer if it solved your issue? :)","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":47,"estimatedTokens":352}}290{"id":"stack-74814171","source":"stackoverflow","questionId":74814171,"title":"How to findUnique on a relation field in Prisma?","tags":["javascript","sql","postgresql","prisma"],"text":"Title: How to findUnique on a relation field in Prisma?\nTags: javascript, sql, postgresql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using Prisma with Postgres and I have a schema something like\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n uuid String @unique @default(uuid())\n house House?\n}\n\nmodel House {\n id Int @id @default(autoincrement())\n user User @relation(fields: [userId], references: [id])\n userId Int @unique\n}\n```\n\nEach house will have a unique user associated with it. I'd like to find the one house that is associated with a unique user i.e.\n\n```\nprisma.house.findUnique({\n where: {\n user: {\n uuid: \n }\n }\n})\n```\n\nBut this doesn't work because the user field on House is not `@unique` and if I try adding `@unique`, prisma says relation fields can't be unique.\n\nSo how do I accomplish finding a unique house given a unique user when relation fields can't be unique? Is there a better way to query this?\n\n========================================\n\nCode:\n```text\nmodel User {\n  id                  Int                  @id @default(autoincrement())\n  uuid                String               @unique @default(uuid())\n  house House?\n}\n\nmodel House {\n  id            Int      @id @default(autoincrement())\n  user          User     @relation(fields: [userId], references: [id])\n  userId        Int      @unique\n}\n```\n\n```text\nprisma.house.findUnique({\n  where: {\n    user: {\n      uuid: <given userId>\n    }\n  }\n})\n```\n\n```text\n@unique\n```\n\n```text\n@unique\n```\n\n```js\nprisma.user.findUnique({\n  where: {\n      uuid: <given userId>\n  },\n  include: {\n    user: true\n }\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":82,"estimatedTokens":400}}291{"id":"stack-74824374","source":"stackoverflow","questionId":74824374,"title":"How do i store custom object in prisma schema?","tags":["javascript","nuxt.js","prisma"],"text":"Title: How do i store custom object in prisma schema?\nTags: javascript, nuxt.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a model called \"Setup\"\n\n```\nmodel Setup {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n userId String? @unique @db.ObjectId\n user User? @relation(fields: [userId], references: [id])\n\n contract String[]\n legal String[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n```\n\nIn this model i want to store an array like\n\n```\nconst contractData = {\n id: '729a4839f3dapob44zt2b4b1',\n name: 'Example Name',\n text: 'Example Text'\n}\n```\n\nso in my above model \"Setup\" i want to store the contractData\n\n```\nprisma.setup.create({\n data: {\n userId: '6399bc74426f71f2da6e316c',\n personal: [],\n contract: contractData,\n legal: []\n }\n })\n```\n\nUnfortunately, this not work.\n\nHow can i define an Object for contract and store this in my database?\n\n========================================\n\nTop Answer:\nthis is old,\n\nquick answer is, it will be best to create a new model for your contractData object and then link to the parent using Prisma's relation.\n\nJSON would be extremely difficult to parse, and you can't just manufacture a data type like \"object\".\n\nLastly, [] is used to indicate a many relationship when suffixed to another model name, not to be confused with the List you have in Js or Ts\n\n========================================\n\nCode:\n```text\nmodel Setup {\n  id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n  userId String? @unique @db.ObjectId\n  user   User?   @relation(fields: [userId], references: [id])\n\n  contract String[]\n  legal    String[]\n\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n}\n```\n\n```text\nconst contractData = {\n    id: '729a4839f3dapob44zt2b4b1',\n    name: 'Example Name',\n    text: 'Example Text'\n}\n```\n\n```text\nprisma.setup.create({\n    data: {\n      userId: '6399bc74426f71f2da6e316c',\n      personal: [],\n      contract: contractData,\n      legal: []\n    }\n  })\n```\n\n```text\nmodel Setup {\n  id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n  userId String? @unique @db.ObjectId\n  user   User?   @relation(fields: [userId], references: [id])\n\n  contract Json[]\n  legal    String[]\n\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n}\n```\n\n```text\nJson\n```\n\n```text\nprisma.setup.create\n```\n\n```text\nSetup\n```\n\n```text\ncontract\n```\n\n```text\nmodel Setup {\n  id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n  userId String? @unique @db.ObjectId\n  user   User?   @relation(fields: [userId], references: [id])\n\n  contract Object[]\n  legal    String[]\n\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n}\n```\n\n```text\nprisma.setup.create({\n  data: {\n    userId: '6399bc74426f71f2da6e316c',\n    personal: [],\n    contract: [contractData],\n    legal: []\n  }\n})\n```\n\n```text\ncontract\n```\n\n```text\n[contractData]\n```\n\n========================================\n\nComments:\n- It is not possible to change the type in schema.prisma to Object[].. i receive the following error message: error: Type \"Object\" is neither a built-in type, nor refers to another model, custom type, or enum. --> schema.prisma:150.. should i install any extentions?\n- What do you mean this is old and how does that help answer the question? And isn't [] also used for lists in Prisma?\n- I believe the first paragraph answered that, and I also said having [ ] behind a model name, doesn't make it a list, it defines it's relationship. What you are describing is [ ] behind a data type like string[] which is a prisma list. So again the easiest way to store multiple Objects instead of JSON directly on the DB, will be to create a separate model","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":168,"estimatedTokens":919}}292{"id":"stack-75153526","source":"stackoverflow","questionId":75153526,"title":"Integration of 'sort by' (and other filters) with SvelteKit","tags":["express","filtering","svelte","prisma","sveltekit"],"text":"Title: Integration of 'sort by' (and other filters) with SvelteKit\nTags: express, filtering, svelte, prisma, sveltekit\nSource: Stack Overflow\n\nQuestion:\nI have a backend route '/products' (using ExpressJS and Prisma) that returns a list of all products, however it also has some query parameters that can be used to specify futher, namely:\n\n- page (and count): used for pagination\n\n- sort and sortDir: used for sorting by a value in a specific direction (desc or asc)\n\n- category: comma separated list of categories to search by\n\nI load the products on the frontend SvelteKit project in `+page.server.ts` and display them in a table format. However, when the user changes, for instance, the sort direction, how would I update the page data using a new route (namely the original one, with sortDir=desc). Is there some way of invalidating the query and replacing it with a new one, with the correct search parameters?\n\nOr is there some other way that this is normally implemented in production?\n\n========================================\n\nCode:\n```text\n+page.server.ts\n```\n\n```text\n// +page.server.js\nexport async function load({ fetch, url }) => {\n  const sortDir = url.searchParams.get(\"sortDir\")\n  return {\n    products: await ...,\n  };\n};\n```\n\n```text\n<a href=\"?sortDir=asc\">ASC</a>\n```\n\n```text\n$app/navigation\n```\n\n========================================\n\nComments:\n- Thanks! Will that append the search param onto the URL, or completely overwrite them? And I'll definitely look into Prisma on the +page.server.js files! That sounds useful :D\n- Overwrite them, so you might need to write a little utility function that generates urls based on the current searchParams. (Readable from the $page.url store)\n- Gotcha! Could it be worth storing them in a writable store, or is that overkill when I could simply parse the current url and modify it accordingly? (More of an opiniated question, I know, but just curious on your thoughts)","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":484}}293{"id":"stack-76197805","source":"stackoverflow","questionId":76197805,"title":"req.body is undefined when fetching method delete in Next.js","tags":["reactjs","typescript","next.js","prisma","next-api"],"text":"Title: req.body is undefined when fetching method delete in Next.js\nTags: reactjs, typescript, next.js, prisma, next-api\nSource: Stack Overflow\n\nQuestion:\nI really don't know why, but when I try to fetch data and put it in the body of my response, it says undefined (in the console). I have almost 2 identical components. One uses a POST method and returns a populated body, the other uses a DELETE method and returns an undefined body. I am using a Prisma schema.\n\nThis is the POST that works and returns a body for the API\n\n```\nexport default function Product({\n id_product,\n name,\n link_image,\n price,\n}: ProductProps) {\n const [test, testing] = useState(false);\n const { push: relocate } = useRouter();\n\n const onAddToCart = async () => {\n\n let response = await fetch(\"/api/addToCart\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n id_product: id_product,\n }),\n });\n\n if (response.ok) {\n toast.success(`${name} was added to the cart`);\n } else {\n toast.error(`${name} is already in your cart`);\n }\n };\n```\n\nThis is start of the API for that function, const { id_product } = req.body works.\n\n```\nasync function handlePost(req: NextApiRequest, res: NextApiResponse) {\n const session = await getServerSession(req, res, authOptions);\n const client = connexion()\n const { id_product } = req.body;\n \n const user = await client.user.findFirst({\n where: { email: session?.user?.email || undefined}\n })\n\n let cart = await client.cart.findFirst({\n where: {id_user: user?.id_user}\n })\n```\n\nAnd this is what I'm having trouble with, the component is basically the same, except the method :\n\n```\ntype ProductProps = products;\n\nexport default function ProductItem({\n id_product,\n description,\n publication_date,\n author,\n name,\n link_image,\n price,\n}: ProductProps) {\n const onDeleteFromCart = async () => {\n let data = {\n id_product: id_product\n }\n let response = await fetch(\"/api/deleteFromCart\", {\n method: \"DELETE\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(data),\n });\n if (response.ok) {\n toast.success(`${name} was succesfully removed from your cart`)\n }\n else {\n toast.error(`Error`);\n }\n };\n```\n\nThis is the API for, const {id_product} = req.body is undefined\n\n```\nasync function handleDelete(req: NextApiRequest, res: NextApiResponse) {\n const session = await getServerSession(req, res, authOptions);\n const client = connexion()\n const { id_product } = req.body\nconsole.log(id_product)\n const user = await client.user.findFirst({\n where: { email: session?.user?.email || undefined}\n });\n \n let cart = await client.cart.findFirst({\n where: {id_user: user?.id_user}\n });\n let cart_item = await client.cart_item.findFirst({\n where: {\n id_cart: cart?.id,\n id_product: id_product\n }\n })\n```\n\nI've been trying to solve this problem for a couple of hours now and I didn't progress at all.\n\n========================================\n\nTop Answer:\nThis used to work until a very recent update. There's a bunch of issues on GIthub but I don't know that any maintainer of Next.js has responded yet. It's currently blocking us from updating. I get that it's not typical, but this is a breaking change by Next.js, and I don't want to have to migrate all our DELETE endpoints :(.\n\nhttps://github.com/vercel/next.js/issues/49353\n\nhttps://github.com/vercel/next.js/issues/48096\n\nhttps://github.com/vercel/next.js/issues/48898\n\n========================================\n\nCode:\n```text\nexport default function Product({\n  id_product,\n  name,\n  link_image,\n  price,\n}: ProductProps) {\n  const [test, testing] = useState(false);\n  const { push: relocate } = useRouter();\n\n  const onAddToCart = async () => {\n\n    let response = await fetch(\"/api/addToCart\", {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify({\n        id_product: id_product,\n      }),\n    });\n\n    if (response.ok) {\n      toast.success(`${name} was added to the cart`);\n    } else {\n      toast.error(`${name} is already in your cart`);\n    }\n  };\n```\n\n```text\nasync function handlePost(req: NextApiRequest, res: NextApiResponse) {\n    const session = await getServerSession(req, res, authOptions);\n    const client = connexion()\n    const { id_product } = req.body;\n \n    const user = await client.user.findFirst({\n        where: { email: session?.user?.email || undefined}\n    })\n\n    let cart = await client.cart.findFirst({\n        where: {id_user: user?.id_user}\n    })\n```\n\n```text\ntype ProductProps = products;\n\nexport default function ProductItem({\n  id_product,\n  description,\n  publication_date,\n  author,\n  name,\n  link_image,\n  price,\n}: ProductProps) {\n  const onDeleteFromCart = async () => {\n    let data = {\n      id_product: id_product\n    }\n    let response = await fetch(\"/api/deleteFromCart\", {\n      method: \"DELETE\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify(data),\n    });\n    if (response.ok) {\n        toast.success(`${name} was succesfully removed from your cart`)\n    }\n    else {\n        toast.error(`Error`);\n      }\n  };\n```\n\n```text\nasync function handleDelete(req: NextApiRequest, res: NextApiResponse) {\n    const session = await getServerSession(req, res, authOptions);\n    const client = connexion()\n    const  { id_product } = req.body\nconsole.log(id_product)\n    const user = await client.user.findFirst({\n        where: { email: session?.user?.email || undefined}\n    });\n \n    let cart = await client.cart.findFirst({\n        where: {id_user: user?.id_user}\n    });\n    let cart_item = await client.cart_item.findFirst({\n        where: {\n            id_cart: cart?.id,\n            id_product: id_product\n        }\n    })\n```\n\n```text\ndelete\n```\n\n```text\npatch\n```\n\n========================================\n\nComments:\n- Delete requests typically don't have a body ...\n- Basically I'm trying to pass the id_product to the body when I click a button. It works when I do a POST method, but doesn't when it's a DELETE.\n- thank you so much, patch request works perfectly!","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":233,"estimatedTokens":1506}}294{"id":"stack-76705749","source":"stackoverflow","questionId":76705749,"title":"Prisma - Set property's type as array of enum","tags":["database","mongodb","prisma"],"text":"Title: Prisma - Set property's type as array of enum\nTags: database, mongodb, prisma\nSource: Stack Overflow\n\nQuestion:\nThis is my model:\n\n```\nmodel ExampleModel {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n name String @unique\n foo ...\n}\n\nenum Tags {\n TagA\n TagB\n TagC\n}\n```\n\nI want to set the type of `foo` as an array of Tags, (an example value of `foo` would be `['TagA', 'TagC']`. How do I do that? Using `foo Tags[]` sets the type of `foo` as `\"TagA\"[] | undefined`\n\n========================================\n\nCode:\n```text\nmodel ExampleModel {\n  id   String @id @default(auto()) @map(\"_id\") @db.ObjectId\n  name String @unique\n  foo  ...\n}\n\nenum Tags {\n  TagA\n  TagB\n  TagC\n}\n```\n\n```text\nfoo\n```\n\n```text\nfoo\n```\n\n```text\n['TagA', 'TagC']\n```\n\n```text\nfoo Tags[]\n```\n\n```text\nfoo\n```\n\n```text\n\"TagA\"[] | undefined\n```\n\n```text\nmodel ExampleModel {\n  id   String @id @default(auto()) @map(\"_id\") @db.ObjectId\n  name String @unique\n  foo  Tags[] @default([])\n}\n\nenum Tags {\n  TagA\n  TagB\n  TagC\n}\n```\n\n```text\nfoo\n```\n\n```text\nTags\n```\n\n```text\nfoo Tags[]\n```\n\n```text\n@default\n```\n\n```text\nfoo\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":97,"estimatedTokens":279}}295{"id":"stack-73606989","source":"stackoverflow","questionId":73606989,"title":"Prisma, Can't use '_count' in 'FindMany' query to get total count of the data","tags":["prisma"],"text":"Title: Prisma, Can't use '_count' in 'FindMany' query to get total count of the data\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\n```\nconst fictions = await client.fiction.findMany({\n **_count: true,**\n take: 18,\n skip: (+page!.toString() - 1 || 0) * 18,\n where: {\n AND: [\n { OR: [...genresMany] },\n {\n OR: [...nationalitiesMany],\n },\n {\n AND: [...keywordMany],\n },\n ],\n },\n include: {\n _count: {\n select: {\n favs: true,\n },\n },\n author: true,\n },\n ...sortingOne(),\n });\n```\n\nI'd like to get total count of the query for pagination. And the manual says the using `_count` is the way.\n\nHowever, it seems `_count` cannot be used in the query, and I can't find out the reason.\n\nIs it a wrong usage?\n\nIf it's wrong, then what can I do for getting the total count of the query (not 18, the taked items)?\n\nShould I count them again with the similar code after the query? I think that's too wasteful.\n\nWould be very thanks if there's any help.\n\n========================================\n\nCode:\n```js\nconst fictions = await client.fiction.findMany({\n      **_count: true,**\n      take: 18,\n      skip: (+page!.toString() - 1 || 0) * 18,\n      where: {\n        AND: [\n          { OR: [...genresMany] },\n          {\n            OR: [...nationalitiesMany],\n          },\n          {\n            AND: [...keywordMany],\n          },\n        ],\n      },\n      include: {\n        _count: {\n          select: {\n            favs: true,\n          },\n        },\n        author: true,\n      },\n      ...sortingOne(),\n    });\n```\n\n```text\n_count\n```\n\n```text\n_count\n```\n\n```text\nconst fictions = await client.fiction.count({\n      where: {\n        AND: [\n          { OR: [...genresMany] },\n          {\n            OR: [...nationalitiesMany],\n          },\n          {\n            AND: [...keywordMany],\n          },\n        ],\n      }\n    });\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":99,"estimatedTokens":456}}296{"id":"stack-71162298","source":"stackoverflow","questionId":71162298,"title":"Using a prisma query with callback seems to ignore try/catch blocks (Node)","tags":["javascript","node.js","try-catch","prisma"],"text":"Title: Using a prisma query with callback seems to ignore try/catch blocks (Node)\nTags: javascript, node.js, try-catch, prisma\nSource: Stack Overflow\n\nQuestion:\nI have this piece of code (the error handler is taken from the prisma docs):\n\n```\ntry {\n prisma.daRevisionare.create({ data: { \"idTweet\": tweet.id, \"testo\": testotweet, url } }).then((dati) => {\n bot.sendMessage(chatId, testotweet, { \"reply_markup\": { \"inline_keyboard\": [[{ \"text\": \"Aggiungi\", \"callback_data\": `si,${dati.id}` }], [{ \"text\": \"Scarta\", \"callback_data\": `no,${dati.id}` }]] } })\n })\n } catch (e) {\n if (e instanceof Prisma.PrismaClientKnownRequestError) {\n if (e.code === 'P2002') {\n console.log(\n 'There is a unique constraint violation, a new user cannot be created with this email'\n )\n }\n }\n }\n```\n\nThe try/catch block should in theory prevent the application from crashing when a unique constraint is violated, but when I try to trigger the error the application just crash:\n\n```\n45 try {\n→ 46 prisma.daRevisionare.create(\n Unique constraint failed on the constraint: `daRevisionare_idTweet_key`\n at cb (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:38703:17)\n at async PrismaClient._request (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:40853:18) {\n code: 'P2002',\n clientVersion: '3.9.1',\n meta: { target: 'daRevisionare_idTweet_key' }\n}\n```\n\nit seems to completely ignore the try/catch block, how can I solve this?\n\n========================================\n\nCode:\n```text\ntry {\n    prisma.daRevisionare.create({ data: { \"idTweet\": tweet.id, \"testo\": testotweet, url } }).then((dati) => {\n      bot.sendMessage(chatId, testotweet, { \"reply_markup\": { \"inline_keyboard\": [[{ \"text\": \"Aggiungi\", \"callback_data\": `si,${dati.id}` }], [{ \"text\": \"Scarta\", \"callback_data\": `no,${dati.id}` }]] } })\n    })\n  } catch (e) {\n    if (e instanceof Prisma.PrismaClientKnownRequestError) {\n      if (e.code === 'P2002') {\n        console.log(\n          'There is a unique constraint violation, a new user cannot be created with this email'\n        )\n      }\n    }\n  }\n```\n\n```text\n45 try {\n→ 46   prisma.daRevisionare.create(\n  Unique constraint failed on the constraint: `daRevisionare_idTweet_key`\n    at cb (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:38703:17)\n    at async PrismaClient._request (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:40853:18) {\n  code: 'P2002',\n  clientVersion: '3.9.1',\n  meta: { target: 'daRevisionare_idTweet_key' }\n}\n```\n\n```text\ntry {\n    await prisma.daRevisionare.create(...)\n}\n```\n\n```text\nprisma.daRevisionare.create(...).then(...).catch(e => {\n    if (e instanceof Prisma.PrismaClientKnownRequestError) {\n      if (e.code === 'P2002') {\n        console.log(\n          'There is a unique constraint violation, a new user cannot be created with this email'\n        )\n      }\n    }\n})\n```\n\n```text\ntry/catch\n```\n\n```text\nawait\n```\n\n```text\nawait\n```\n\n```text\ncatch\n```\n\n```text\ntry/catch\n```\n\n========================================\n\nComments:\n- Even with await I have this problem\n- I have the same issue.","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":113,"estimatedTokens":803}}297{"id":"stack-58449715","source":"stackoverflow","questionId":58449715,"title":"Cannot receive error from GraphQL with graphql-middleware-sentry","tags":["reactjs","graphql","apollo","react-apollo","prisma"],"text":"Title: Cannot receive error from GraphQL with graphql-middleware-sentry\nTags: reactjs, graphql, apollo, react-apollo, prisma\nSource: Stack Overflow\n\nQuestion:\n**Note:** The problem was in graphql-middleware-sentry not forwarding on the errors. The solution is below and marked as the correct answer.\n\nI'm currently handling a form using React and Apollo React Hooks on the frontend, and a mixture of GraphQL-Yoga and Prisma on the backend. The mutation works fine, and the form is ok. But I cannot receive errors thrown by the backend in React.\n\nI've tried various error types but I haven't had much luck. For example, my mutation in react looks like this:\n\n```\nconst [requestPasswordResetMutation, { data, error, loading }] = useMutation(\n REQUEST_PASSWORD_REQUEST,\n {\n errorPolicy: 'all',\n },\n )\n```\n\nOn the backend, I might want to throw an error where an email address isn't recognised. I run a simple check such as:\n\n```\nif (!user) {\n throw Error('User not found')\n }\n```\n\nThis error is successfully triggered and picked up by Sentry. But no error is detected by the frontend in the `errors` variable. Instead, the form acts as though it is successfully submitted (given the absence of values in the `errors` object.\n\nCan anyone give me a pointer on how I'm meant to be communicating errors from the backend to the frontend here?\n\nResolver code:\n\n```\nconst requestPasswordReset = async (parent, { email }, context) => {\n const user = await context.prisma.user({\n email,\n })\n\n if (!user) {\n throw new Error('User not found')\n }\n\n const passwordResetToken = crypto.randomBytes(20).toString('hex')\n const passwordTokenExpiry = expiryDate()\n\n try {\n await context.prisma.updateUser({\n data: {\n passwordResetToken,\n passwordTokenExpiry,\n },\n where: {\n email: user.email,\n },\n })\n } catch (error) {\n console.error(error)\n }\n\n if (process.env.NODE_ENV === 'production') {\n // Send email\n }\n\n return {\n message: 'Reset token sent',\n }\n}\n```\n\n========================================\n\nCode:\n```text\nconst [requestPasswordResetMutation, { data, error, loading }] = useMutation(\n    REQUEST_PASSWORD_REQUEST,\n    {\n      errorPolicy: 'all',\n    },\n  )\n```\n\n```text\nif (!user) {\n    throw Error('User not found')\n  }\n```\n\n```text\nconst requestPasswordReset = async (parent, { email }, context) => {\n  const user = await context.prisma.user({\n    email,\n  })\n\n  if (!user) {\n    throw new Error('User not found')\n  }\n\n  const passwordResetToken = crypto.randomBytes(20).toString('hex')\n  const passwordTokenExpiry = expiryDate()\n\n  try {\n    await context.prisma.updateUser({\n      data: {\n        passwordResetToken,\n        passwordTokenExpiry,\n      },\n      where: {\n        email: user.email,\n      },\n    })\n  } catch (error) {\n    console.error(error)\n  }\n\n  if (process.env.NODE_ENV === 'production') {\n    // Send email\n  }\n\n  return {\n    message: 'Reset token sent',\n  }\n}\n```\n\n```text\nerrors\n```\n\n```text\nerrors\n```\n\n```text\nconst sentryMiddleware = sentry({\n  forwardErrors: true,\n  ...\n})\n```\n\n```text\ngraphql-middleware-sentry\n```\n\n```text\nforwardErrors\n```\n\n```text\nfalse\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Is the error listed in the `errors` array inside the response? You can see the whole response from the server inside the Network tab of your browser's DevTools.\n- Hi Daniel, I actually get no response, other than a null value for the message I want to send back. For example, it would normally return `message: 'Reset token sent'`. Instead it returns: `message: null`.\n- So you *are* getting a response, just that the `data` property looks like this: `{ \"message\": null }`. However, the response from the server can also include an `errors` array in addition to the `data` object. So I'm asking if there is an `errors` array in the response and if so, what its contents are. The only way to verify this is by looking at your DevTools.\n- Hey, so the response doesn't contain an errors array. The only thing getting returned in the response (looking at the network tab in DevTools) is `{\"data\":{\"requestPasswordReset\":null}}`\n- Ok. So that's why Apollo is not showing any errors. Somewhere along the line, the error you're throwing inside the resolver is being swallowed up instead of being caught by your GraphQL service. If I had to bet, I'd say you're using a try/catch and not throwing the error again. Please update your question with the code for the resolver in question.\n- If you're using something like graphql-middleware, that might also be swallowing the error.\n- Ahh that makes sense. I've updated my question with the resolver code. Only middlewares I'm using are the sentry error handler, and graphql-shield.\n- This looks as though it's the sentry middleware which is swallowing the error!\n- Yup, I posted an answer. It might be helpful to update the question body and title to reflect the true issue -- something like \"Cannot receive error from GraphQL with graphql-middleware-sentry\". That might help folks having the same issue find your question.","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":169,"estimatedTokens":1255}}298{"id":"stack-55045414","source":"stackoverflow","questionId":55045414,"title":"GraphQL & Prisma: why does one redefine types in the application schema when they are already part of the Prisma database schema?","tags":["graphql","prisma","prisma-graphql"],"text":"Title: GraphQL & Prisma: why does one redefine types in the application schema when they are already part of the Prisma database schema?\nTags: graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nHi — I’ve been following along with a GraphQL/Prisma tutorial (https://www.howtographql.com/graphql-js/6-authentication/) and I’m wondering why one redefines types in the application schema when they are already part of the Prisma database schema and could be imported from there. \n\nThe answer the tutorial gives is “To hide potentially sensitive information from client applications”. What does this mean exactly? Why do we replicate definitions in ‘schema.graphql’ and ‘datamodel.prisma’? Because the definitions are slightly different (i.e. the 'datamodel' contains tags like `@unique`)? And how are we hiding things from client applications? I remain perplexed....\n\nSpecifically in ‘schema.graphql’ I have\n\n```\ntype User {\n id: ID!\n name: String!\n email: String!\n links: [Link!]!\n}\n```\n\nand in 'datamodel.prisma' I have\n\n```\ntype User {\n id: ID! @unique\n name: String!\n email: String! @unique\n password: String!\n links: [ Link!] !\n}\n```\n\n========================================\n\nCode:\n```text\ntype User {\n    id: ID!\n    name: String!\n    email: String!\n    links: [Link!]!\n}\n```\n\n```text\ntype User {\n    id: ID! @unique\n    name: String!\n    email: String! @unique\n    password: String!\n    links: [ Link!] !\n}\n```\n\n```text\n@unique\n```\n\n```text\npassword\n```\n\n========================================\n\nComments:\n- The schema doesn't have the password, that is likely what is meant by \"hide potentially sensitive information\". This is common practice in any API to not return *all* data from the persistent storage.\n- Ah, of course! It still seems odd to me, having almost the same definition in two separate places, but I see what you mean.\n- So basically the models defined in 'schema.graphql' contain only those things that you need to know about, whereas those in 'datamodel.prisma' contain *everything* that is to be stored?\n- Basically yes. In this case, you would never show the password field. I would hope it's hashed anyway so the only thing you should do is pass another hashed password in, along with a username or email and confirm a match.","metadata":{"transformedAt":"2026-08-18T18:33:14.846Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":69,"estimatedTokens":567}}299{"id":"stack-71100950","source":"stackoverflow","questionId":71100950,"title":"how to type prisma objects in parameters","tags":["prisma"],"text":"Title: how to type prisma objects in parameters\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nI have a function that expects a prisma model / instance\n\nHow do I actually type this function signature? What I want is the type that is returned from a `prisma.SOMETABLE.find` like:\n\n`const item = await prisma.nftCollection.findFirst()`\n\nshort code snippet below.\n\n```\nimport { Prisma, PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n\nexport class Buyer {\n\n async findColl() {\n const item = await prisma.nftCollection.findFirst()\n await this.buyItem(item)\n }\n\n // this is the param i want to type\n async buyItem(item: SOMETYPE) {\n clog.info('todo - buy', item)\n }\n}\n```\n\nmore detail here:\nhttps://github.com/prisma/prisma/discussions/11737\n\n========================================\n\nCode:\n```js\nimport { Prisma, PrismaClient } from '@prisma/client'\nconst prisma = new PrismaClient()\n\nexport class Buyer {\n\n    async findColl() {\n        const item = await prisma.nftCollection.findFirst()\n        await this.buyItem(item)\n    }\n\n    // this is the param i want to type\n    async buyItem(item: SOMETYPE) {\n        clog.info('todo - buy', item)\n    }\n}\n```\n\n```text\nprisma.SOMETABLE.find\n```\n\n```text\nconst item = await prisma.nftCollection.findFirst()\n```\n\n```js\nimport { Prisma, PrismaClient, Item } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nexport class Buyer {\n\n  async findColl(): Promise<void> {\n    const item = await prisma.nftCollection.findFirst();\n    await this.buyItem(item);\n  }\n\n  async buyItem(item: Item | null): Promise<void> {\n    clog.info('todo - buy', item);\n  }\n}\n```\n\n```text\nItem\n```\n\n```text\nItem\n```\n\n```text\n@prisma/client\n```\n\n```text\nbuyItem\n```\n\n```text\nItem | null\n```\n\n```text\nfindFirst\n```\n\n```text\nItem\n```\n\n```text\nnull\n```\n\n```text\nitem\n```\n\n```text\nnull\n```\n\n```text\nbuyItem\n```\n\n```text\nitem: Item\n```\n\n```text\nfindFirst\n```\n\n```text\nPartial<Item>\n```\n\n```text\nItem\n```\n\n```text\ncollection\n```\n\n```text\ntype collection { ... }\n```\n\n========================================\n\nComments:\n- OK that first line is what I needed. Are there any good guides on how to define your own models that sit on top of imported prisma types? coming from a datamapper or sequelize view. most of the tuts on prisma site are pretty basic.\n- Unfortunately I do not know any good guides which go beyond the basic stuff. But what I do like is to map my models the following: `model Collection { ... @@map(\"collection\") }` or `model Item { ... @@map(\"items\") }`. Importing `Collection` or `Item` feels a bit more natural.","metadata":{"transformedAt":"2026-08-18T18:33:14.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":154,"estimatedTokens":643}}300{"id":"stack-56464407","source":"stackoverflow","questionId":56464407,"title":"How to resolve subselections / relations in prisma (nested lists)","tags":["graphql","prisma","prisma-graphql"],"text":"Title: How to resolve subselections / relations in prisma (nested lists)\nTags: graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nLet's take an example from the github repo of prisma:\n\nWe have a user, the user could have multiple posts, and one post could have multiple links.\n\nMy goal is, to retrieve all posts and all links.\nThis means, my response is a list (links) in a list (posts).\n\nI want to map the values I get back as two nested lists.\n\n**datamodel.prisma**\n\n```\ntype User {\n id: ID! @id\n email: String! @unique\n name: String\n posts: [Post]!\n}\n\ntype Post {\n id: ID! @id\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n published: Boolean! @default(value: false)\n title: String!\n content: String\n author: User!\n links: [Link]!\n}\n\ntype Link {\n id: ID! @id\n url: String\n title: String\n post: Post!\n}\n```\n\n**schema.graphql**\n\n```\ntype Query {\n ...\n}\n\ntype Mutation {\n ...\n}\n\ntype Link {\n id: ID!\n url: String\n title: String\n post: Post!\n}\n\ntype Post {\n id: ID!\n createdAt: DateTime!\n updatedAt: DateTime!\n published: Boolean!\n title: String!\n content: String\n author: User!\n}\n\ntype User {\n id: ID!\n email: String!\n name: String\n posts: [Post]!\n}\n```\n\nI want to query **all posts** of a user, and all of the links for every post in the response.\n\nHow would I query this request?\n\n```\nuser {\n id\n posts {\n id\n links {\n id\n }\n }\n}\n```\n\nThe above code snipper would not work.\n\n**EDIT**\nI want to use the following:\n\n```\nUser: {\n listPosts: (parent, args, context, info) {\n return context.prisma.posts().links()\n }\n}\n```\n\nSo in my response (data in front-end via react-apollo Query Component), I want to map over posts AND the links in each post.\n\nBUT the links attribute in posts is null.\n\nIs there another way to achieve this?!\n\n========================================\n\nCode:\n```js\ntype User {\n  id: ID! @id\n  email: String! @unique\n  name: String\n  posts: [Post]!\n}\n\ntype Post {\n  id: ID! @id\n  createdAt: DateTime! @createdAt\n  updatedAt: DateTime! @updatedAt\n  published: Boolean! @default(value: false)\n  title: String!\n  content: String\n  author: User!\n  links: [Link]!\n}\n\ntype Link {\n  id: ID! @id\n  url: String\n  title: String\n  post: Post!\n}\n```\n\n```js\ntype Query {\n  ...\n}\n\ntype Mutation {\n  ...\n}\n\ntype Link {\n  id: ID!\n  url: String\n  title: String\n  post: Post!\n}\n\ntype Post {\n  id: ID!\n  createdAt: DateTime!\n  updatedAt: DateTime!\n  published: Boolean!\n  title: String!\n  content: String\n  author: User!\n}\n\ntype User {\n  id: ID!\n  email: String!\n  name: String\n  posts: [Post]!\n}\n```\n\n```text\nuser {\n  id\n  posts {\n    id\n    links {\n      id\n    }\n  }\n}\n```\n\n```js\nUser: {\n  listPosts: (parent, args, context, info) {\n    return context.prisma.posts().links()\n  }\n}\n```\n\n```text\nconst fragment = `\nfragment UserWithPostsAndLinks on User {\n  id\n  email\n  name\n  posts {\n    id\n    title\n    content\n    links {\n      id\n      url\n      title\n    }\n  }\n}\n`\n\nconst userWithPostsAndLinks = await prisma.user({ id: args.id }).$fragment(fragment)\n```\n\n```text\n$fragment\n```\n\n========================================\n\nComments:\n- @DanielRearden Prisma defaults to an inline relation, so in this case, this is not necessary.\n- Can you clarify what's not working? What errors are you seeing? How are you actually using the above query inside your resolver?\n- @DanielRearden updated my question. Thx.","metadata":{"transformedAt":"2026-08-18T18:33:14.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":230,"estimatedTokens":836}}301{"id":"stack-69976801","source":"stackoverflow","questionId":69976801,"title":"Prisma : select on many to many with multiple conditions","tags":["typescript","next.js","prisma"],"text":"Title: Prisma : select on many to many with multiple conditions\nTags: typescript, next.js, prisma\nSource: Stack Overflow\n\nQuestion:\nI have two tables `User` and `Post` that are linked by a custom many to many table such as :\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n name String\n enabled Bool\n posts users_to_posts[]\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n name String\n enabled Bool\n users users_to_posts[]\n}\n\nmodel user_to_post {\n user user? @relation(fields: [user_id], references: [id])\n user_id Int\n post post? @relation(fields: [post_id], references: [id])\n post_id Int\n @@id([user_id, post_id])\n}\n```\n\nI am attempting to get a list of users based on a list of post Ids where the users and the posts must be enabled.\n\nSo far I can get the right users that are enabled if they have a post that is in the given post array but I cannot check if the post is enabled or not nor can I filter the posts ( I get all of the posts associated with the user if there is a match )\n\nHere is the ( almost ) working code I have :\n\n```\nimport { PrismaClient, Prisma } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\nexport default async function handler(req, res) {\n if (req.method !== 'POST') {\n res.status(400).send({ message: 'Only POST requests allowed for this route' })\n } else {\n const { posts_id } = req.query\n const posts_array = posts_id.split(\",\").map(function(item) {\n return parseInt(item)\n })\n const ret = await prisma.user.findMany({\n where: {\n enabled: true,\n post: { some: { post_id: { in: posts_array } }, },\n },\n include: {\n _count: { select: { post: true } }\n post: { select: { post: true }, },\n },\n })\n res.status(200).send(ret)\n // ...\n }\n}\n```\n\nI am still battling to understand how I can multiple embedded selections without having to rely on typescript to get the query working properly ( witch is far from ideal )\n\n========================================\n\nCode:\n```text\nmodel User {\n  id            Int      @id @default(autoincrement())\n  name          String\n  enabled       Bool\n  posts         users_to_posts[]\n}\n\nmodel Post {\n  id            Int      @id @default(autoincrement())\n  name          String\n  enabled       Bool\n  users         users_to_posts[]\n}\n\nmodel user_to_post {\n  user          user? @relation(fields: [user_id], references: [id])\n  user_id       Int\n  post          post? @relation(fields: [post_id], references: [id])\n  post_id       Int\n  @@id([user_id, post_id])\n}\n```\n\n```text\nimport { PrismaClient, Prisma } from '@prisma/client'\n\nconst prisma = new PrismaClient()\n\nexport default async function handler(req, res) {\n    if (req.method !== 'POST') {\n        res.status(400).send({ message: 'Only POST requests allowed for this route' })\n    } else {\n        const { posts_id } = req.query\n        const posts_array = posts_id.split(\",\").map(function(item) {\n            return parseInt(item)\n        })\n        const ret = await prisma.user.findMany({\n            where: {\n                enabled: true,\n                post: { some: { post_id: { in: posts_array } }, },\n            },\n            include: {\n                _count: { select: { post: true } }\n                post: { select: { post: true }, },\n            },\n        })\n        res.status(200).send(ret)\n        // ...\n    }\n}\n```\n\n```text\nUser\n```\n\n```text\nPost\n```\n\n```js\nconst users = await prisma.user.findMany({\n    where: {\n        enabled: true,\n        posts: {\n            some: {\n                post_id: { in: posts_array },\n                post: {  \n                    enabled: true  // for constraint 1 (only check/match against the post_ids in post array which are enabled)\n                }\n            },\n        },\n\n    },\n\n    include: {\n        _count: { select: { posts: true } },\n        posts: {\n            select: { post: true },\n            where: {\n                post: {  \n                    enabled: true   // for constraint 2 (only include the posts which are enabled)\n                }\n            }\n        },\n    },\n})\n```\n\n```text\nuser\n```\n\n```text\nposts_array\n```\n\n```text\nuser\n```\n\n```text\nenabled\n```\n\n```text\nusers[SOME_IDX]._count.posts\n```\n\n```text\ndisabled\n```\n\n```text\nusers[SOME_IDX].posts\n```\n\n```text\nuser_to_post\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":192,"estimatedTokens":1054}}302{"id":"stack-60360786","source":"stackoverflow","questionId":60360786,"title":"How to set up a different database for testing in prisma?","tags":["node.js","mocha.js","prisma","express-graphql","prisma-graphql"],"text":"Title: How to set up a different database for testing in prisma?\nTags: node.js, mocha.js, prisma, express-graphql, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI want to use a different database for testing my app instead of local database.\n\nthis is my env file\n\n```\n# Environment\nNODE_ENV=development\n\n# Backend\nAPI_PORT=4000\nAPP_SECRET=omg\nDASHBOARD_URL=http://localhost:1234\n\n# Prisma\nPRISMA_ENDPOINT=http://localhost:4466\nPRISMA_SECRET=omg\nPRISMA_MANAGEMENT_API_SECRET=omg\n```\n\nwhat I have tried is changing the Prisma endpoint into `http://localhost:4466/default/test`\n\nbut, then how to dynamically change the endpoint? so that when I need to run the app it will point to that `http://localhost:4466/default/default` and when I need to run test suits it will point to that `http://localhost:4466/default/test` endpoint.\n\n========================================\n\nCode:\n```text\n# Environment\nNODE_ENV=development\n\n# Backend\nAPI_PORT=4000\nAPP_SECRET=omg\nDASHBOARD_URL=http://localhost:1234\n\n# Prisma\nPRISMA_ENDPOINT=http://localhost:4466\nPRISMA_SECRET=omg\nPRISMA_MANAGEMENT_API_SECRET=omg\n```\n\n```text\nhttp://localhost:4466/default/test\n```\n\n```text\nhttp://localhost:4466/default/default\n```\n\n```text\nhttp://localhost:4466/default/test\n```\n\n```text\nhttp://localhost:4466/default/default\n```\n\n```text\nhttp://localhost:4466/default/test\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.847Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":65,"estimatedTokens":337}}303{"id":"stack-67975742","source":"stackoverflow","questionId":67975742,"title":"Optimize SQL queries using GraphQL, Nexus and Prisma","tags":["javascript","graphql","nexus","prisma"],"text":"Title: Optimize SQL queries using GraphQL, Nexus and Prisma\nTags: javascript, graphql, nexus, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to apply some SQL optimization for GraphQL queries containing relations. I use Prisma (v. 2.24.1), Nexus (v. 1.0.0), nexus-plugin-prisma (v. 0.35.0) and graphql (v. 15.5.0).\n\nschema.prisma:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n username String\n firstName String?\n lastName String?\n password String\n email String\n organization Organization @relation(fields: [organizatonId], references: [id])\n organizatonId Int\n}\n\nmodel Organization {\n id Int @id @default(autoincrement())\n name String @unique\n users User[]\n}\n```\n\nWhen I try to perform a simple GraphQL query, which fetches the current organization with users, prisma generates an SQL query which asks for all of the users' columns even though I ask only for the ID.\n\nquery:\n\n```\n{\n organization {\n id\n name\n users {\n id\n }\n }\n}\n```\n\nsql:\n\n```\nSELECT \"public\".\"Organization\".\"id\", \"public\".\"Organization\".\"name\" FROM \"public\".\"Organization\" WHERE 1=1 LIMIT $1 OFFSET $2\nSELECT \"public\".\"Organization\".\"id\" FROM \"public\".\"Organization\" WHERE \"public\".\"Organization\".\"id\" = $1 LIMIT $2 OFFSET $3\nSELECT \"public\".\"User\".\"id\", \"public\".\"User\".\"username\", \"public\".\"User\".\"firstName\", \"public\".\"User\".\"lastName\", \"public\".\"User\".\"password\", \"public\".\"User\".\"email\", \"public\".\"User\".\"organizatonId\" FROM \"public\".\"User\" WHERE \"public\".\"User\".\"organizatonId\" IN ($1) OFFSET $2\n```\n\nFor the resolver I use the `t.model` syntax:\n\n```\nimport { objectType } from \"nexus\"\n\nexport const Organization = objectType({\n name: 'Organization',\n definition(t) {\n t.model.id()\n t.model.name()\n t.model.users()\n }\n})\n```\n\nAs for now, I've found that when using the `t.list.field` syntax with the `resolve` function I can get the requested user fields from the `info` argument, but it seems there is no elegant way to pass that data to prisma client.\n\n```\nt.list.field('users', {\n type: 'User',\n resolve(org, args, ctx, info) {\n // info contains the requested fields\n return ctx.prisma.organization.findUnique({\n where: { id: org.id }\n }).users()\n }\n})\n```\n\nIs there a way to use the data from `info` and query only the `user.id` field?\n\n========================================\n\nCode:\n```text\nmodel User {\n  id             Int           @id @default(autoincrement())\n  username       String\n  firstName      String?\n  lastName       String?\n  password       String\n  email          String\n  organization   Organization  @relation(fields: [organizatonId], references: [id])\n  organizatonId  Int\n}\n\nmodel Organization {\n  id        Int     @id @default(autoincrement())\n  name      String  @unique\n  users     User[]\n}\n```\n\n```text\n{\n  organization {\n    id\n    name\n    users {\n      id\n    }\n  }\n}\n```\n\n```text\nSELECT \"public\".\"Organization\".\"id\", \"public\".\"Organization\".\"name\" FROM \"public\".\"Organization\" WHERE 1=1 LIMIT $1 OFFSET $2\nSELECT \"public\".\"Organization\".\"id\" FROM \"public\".\"Organization\" WHERE \"public\".\"Organization\".\"id\" = $1 LIMIT $2 OFFSET $3\nSELECT \"public\".\"User\".\"id\", \"public\".\"User\".\"username\", \"public\".\"User\".\"firstName\", \"public\".\"User\".\"lastName\", \"public\".\"User\".\"password\", \"public\".\"User\".\"email\", \"public\".\"User\".\"organizatonId\" FROM \"public\".\"User\" WHERE \"public\".\"User\".\"organizatonId\" IN ($1) OFFSET $2\n```\n\n```text\nimport { objectType } from \"nexus\"\n\nexport const Organization = objectType({\n  name: 'Organization',\n  definition(t) {\n    t.model.id()\n    t.model.name()\n    t.model.users()\n  }\n})\n```\n\n```text\nt.list.field('users', {\n  type: 'User',\n  resolve(org, args, ctx, info) {\n    // info contains the requested fields\n    return ctx.prisma.organization.findUnique({\n       where: { id: org.id }\n    }).users()\n  }\n})\n```\n\n```text\nt.model\n```\n\n```text\nt.list.field\n```\n\n```text\nresolve\n```\n\n```text\ninfo\n```\n\n```text\ninfo\n```\n\n```text\nuser.id\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":171,"estimatedTokens":971}}304{"id":"stack-55032153","source":"stackoverflow","questionId":55032153,"title":"Prisma graphql computed fields","tags":["graphql","apollo","apollo-client","prisma","prisma-graphql"],"text":"Title: Prisma graphql computed fields\nTags: graphql, apollo, apollo-client, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI have this datamodel:\n\n```\ntype Item {\n id: ID! @unique\n title: String!\n description: String!\n user: User!\n pictures: [Picture]\n basePrice: Int!\n addons: [Addon]\n}\n```\n\nI'm writing a query called parsedItem that takes the id from arguments and looks for the Item (using the default query for Item generated by Prisma), something like this:\n\n```\nconst where = { id: args.id };\n const item = await ctx.db.query.item({ where }, \n `{\n id\n title\n ...\n```\n\nI need to show on the frontend a computed value: \"dynamicPrice\" it depends on the quantity of the Addons that the Item has.\ne.g: \nItem #1 has 3 addons, each addons has a value of $5. This calculated value should be\n\n```\ndynamicPrice = basePrice + 3 * 5\n```\n\nThe Addon relation could change, so I need to compute this in every request the frontend makes.\n\nI'd like so much to do something like:\n\n```\nitem.dynamicPrice = item.basePrice + (item.addons.length * 5)\n```\n\nand return this **item** in the resolver, but this doesn't work. That throw an error:\n\n \"message\": \"Cannot query field \\\"dynamicPrice\\\" on type \\\"Item\\\".\"\n (*when I try to query the Item from the frontend*)\n\nThis error message makes me think: Should I create dynamicPrice as a field on the datamodel? Can I then populate this field in the query resolver? I know I can, but is this a good approach?\n\nThis is an example, I need to create more computed values for this Item model.\n\n**What is the best scalable solution/workaround for this simple use case?**\n\n========================================\n\nCode:\n```text\ntype Item {\n  id: ID! @unique\n  title: String!\n  description: String!\n  user: User!\n  pictures: [Picture]\n  basePrice: Int!\n  addons: [Addon]\n}\n```\n\n```text\nconst where = { id: args.id };\n const item = await ctx.db.query.item({ where }, \n    `{\n      id\n      title\n      ...\n```\n\n```text\ndynamicPrice = basePrice + 3 * 5\n```\n\n```text\nitem.dynamicPrice = item.basePrice + (item.addons.length * 5)\n```\n\n```text\nconst resolvers = {\n  Query: {\n    parsedItem: (parent, args, ctx, info) => {\n      ...\n    }\n    ...\n  },\n  Item: {\n    dynamicPrice: parent => parent.basePrice + parent.addons.length * 5\n  }\n}\n```\n\n```text\ndynamicPrice\n```\n\n```text\nItem\n```\n\n========================================\n\nComments:\n- It seems that this is the best way, I had to move some parts because of the structure of my project but I ended up using fragment like the documentation says. Thanks @galkin","metadata":{"transformedAt":"2026-08-18T18:33:14.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":115,"estimatedTokens":636}}305{"id":"stack-79843115","source":"stackoverflow","questionId":79843115,"title":"Next.js 15 build fails on Windows during Azure deployment with EPERM symlink error using pnpm and standalone output","tags":["next.js","azure-pipelines","azure-web-app-service","prisma","pnpm"],"text":"Title: Next.js 15 build fails on Windows during Azure deployment with EPERM symlink error using pnpm and standalone output\nTags: next.js, azure-pipelines, azure-web-app-service, prisma, pnpm\nSource: Stack Overflow\n\nQuestion:\nI’m trying to deploy a Next.js 15.2.4 application to Azure App Service, and my production build is failing locally on Windows with a symlink permission error.\n\n### Environment\n\nOS: Windows 11\n\nFramework: Next.js 15.2.4\n\nPackage manager: pnpm\n\nNode version: v20.x\n\nDeployment target: Azure App Service (Linux)\n\nDatabase: Prisma + PostgreSQL\n\nOutput mode: standalone\n\n### **Error I'm Getting**\n\n```\n⚠ Failed to copy traced files for build/server/pages/_app.js\nError: EPERM: operation not permitted, symlink\n'C:\\Users\\...\\node_modules\\.pnpm\\react@19.2.0\\node_modules\\react' ->\n'C:\\Users\\...\\build\\standalone\\node_modules\\react'\n\n⚠ Failed to copy traced files for build/server/pages/_error.js\nError: EPERM: operation not permitted, symlink\n'C:\\Users\\...\\node_modules\\.pnpm\\@opentelemetry+api@1.9.0\\node_modules\\@opentelemetry\\api' ->\n'C:\\Users\\...\\build\\standalone\\node_modules\\.pnpm\\next@15.2.4...\\node_modules\\@opentelemetry\\api'\n\nBuild error occurred\nELIFECYCLE Command failed with exit code 1\n```\n\n### Build Command\n\n```\npnpm run build\n```\n\n### next.config.js\n\n```\n/** @type {import('next').NextConfig} */\nconst nextConfig = {\n output: \"standalone\",\n};\n\nmodule.exports = nextConfig;\n```\n\n### What I Have Tried\n\nRunning terminal as Administrator\n\nReinstalling dependencies:\n\n```\nrm -rf node_modules .next\npnpm install\npnpm run build\n```\n\n- Confirmed Node and pnpm versions\n\n### What I’m Trying to Achieve\n\nI want a portable production build that I can deploy to Azure App Service, but Windows is blocking symlink creation during the standalone build.\n\n========================================\n\nCode:\n```text\n⚠ Failed to copy traced files for build/server/pages/_app.js\nError: EPERM: operation not permitted, symlink\n'C:\\Users\\...\\node_modules\\.pnpm\\react@19.2.0\\node_modules\\react' ->\n'C:\\Users\\...\\build\\standalone\\node_modules\\react'\n\n⚠ Failed to copy traced files for build/server/pages/_error.js\nError: EPERM: operation not permitted, symlink\n'C:\\Users\\...\\node_modules\\.pnpm\\@opentelemetry+api@1.9.0\\node_modules\\@opentelemetry\\api' ->\n'C:\\Users\\...\\build\\standalone\\node_modules\\.pnpm\\next@15.2.4...\\node_modules\\@opentelemetry\\api'\n\nBuild error occurred\nELIFECYCLE Command failed with exit code 1\n```\n\n```text\npnpm run build\n```\n\n```text\n/** @type {import('next').NextConfig} */\nconst nextConfig = {\n  output: \"standalone\",\n};\n\nmodule.exports = nextConfig;\n```\n\n```text\nrm -rf node_modules .next\npnpm install\npnpm run build\n```\n\n```text\nnode-linker = hoisted\n```\n\n```text\n.npmrc\n```\n\n========================================\n\nComments:\n- Thanks. Adding the `.npmrc` file with: `node-linker = hoisted` resolved the issue for me. The build now completes successfully on Windows. Appreciate the help.","metadata":{"transformedAt":"2026-08-18T18:33:14.849Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":124,"estimatedTokens":732}}306{"id":"stack-78681345","source":"stackoverflow","questionId":78681345,"title":"Docker Compose suddenly having trouble with Prisma and Jose","tags":["docker","docker-compose","prisma","jose"],"text":"Title: Docker Compose suddenly having trouble with Prisma and Jose\nTags: docker, docker-compose, prisma, jose\nSource: Stack Overflow\n\nQuestion:\nI have a dockerized Next.js project using Prisma. I was working on it as usual, didn't change anything about the Docker setup, the file locations or packages, I just wanted to rebuild the container to pull new environment variables.\n\nThen I receive this error:\n\n```\n90.79 > hey-shop@0.1.0 postinstall\n90.79 > prisma generate\n90.79 \n91.03 Error: Could not find Prisma Schema that is required for this command.\n91.03 You can either provide it with `--schema` argument, set it as `prisma.schema` in your package.json or put it into the default location.\n91.03 Checked following paths:\n91.03 \n91.03 schema.prisma: file not found\n91.03 prisma/schema.prisma: file not found\n91.03 prisma/schema: directory not found\n91.03 \n91.03 See also https://pris.ly/d/prisma-schema-location\n91.03 npm notice\n91.03 npm notice New minor version of npm available! 10.7.0 -> 10.8.1\n91.03 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.8.1\n91.03 npm notice To update run: npm install -g npm@10.8.1\n91.03 npm notice\n91.03 npm error code 1\n91.03 npm error path /app\n91.03 npm error command failed\n91.03 npm error command sh -c prisma generate\n91.04 \n91.04 npm error A complete log of this run can be found in: /root/.npm/_logs/2024-06-28T08_02_21_293Z-debug-0.log\n------\nfailed to solve: process \"/bin/sh -c npm install\" did not complete successfully: exit code: 1\n```\n\nThis is my package.json scripts section:\n\n```\n\"scripts\": {\n \"dev\": \"next dev\",\n \"build\": \"next-swagger-doc-cli next-swagger-doc.json && next build\",\n \"start\": \"next start\",\n \"lint\": \"next lint\",\n \"resetdb\": \"cross-env NODE_ENV=test npx prisma db push --force-reset && npx prisma db seed\",\n \"postinstall\": \"prisma generate\",\n \"generate-docs\": \"next-swagger-doc-cli next-swagger-doc.json\",\n \"test\": \"cross-env NODE_ENV=test jest\",\n \"test:watch\": \"cross-env NODE_ENV=test jest --watch\"\n },\n \"prisma\": {\n \"seed\": \"tsx prisma/seed.ts\"\n },\n```\n\nUntil then I had no issues running these scripts. It also makes no difference to the error when I specify --schema='/prisma/schema.prisma'. My file structure is the following:\n\n/root\n\npackage.json\n\n/prisma\n\n- schema.prisma\n\nWhen I remove the postinstall script, this part seems to work. I don't need the postinstall anymore anyways - it was for generating an erd, but the corresponding package has vulnerabilities.\n\nHowever, now my auth middleware creates trouble, especially Jose, which I use for JWTs.\n\n```\nweb-1 | ○ Compiling / ...\nweb-1 | ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1 | \nweb-1 | Import trace for requested module:\nweb-1 | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1 | ./node_modules/jose/dist/node/esm/index.js\nweb-1 | ./app/lib/auth.ts\nweb-1 | ./app/lib/utils/api-authorization.ts\nweb-1 | ./app/(general)/layout.tsx\nweb-1 | ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1 | \nweb-1 | Import trace for requested module:\nweb-1 | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1 | ./node_modules/jose/dist/node/esm/index.js\nweb-1 | ./app/lib/auth.ts\nweb-1 | ./app/ui/search/pagination.tsx\nweb-1 | ./app/(general)/page.tsx\nweb-1 | ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1 | \nweb-1 | Import trace for requested module:\nweb-1 | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1 | ./node_modules/jose/dist/node/esm/index.js\nweb-1 | ./app/lib/auth.ts\nweb-1 | ./app/ui/search/pagination.tsx\nweb-1 | ./app/(general)/page.tsx\nweb-1 | ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1 | \nweb-1 | Import trace for requested module:\nweb-1 | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1 | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1 | ./node_modules/jose/dist/node/esm/index.js\nweb-1 | ./app/lib/auth.ts\nweb-1 | ./app/ui/search/pagination.tsx\nweb-1 | ./app/(general)/page.tsx\n```\n\nAnd this is the part where I get stuck. I don't understand why suddenly this error appears. I am on a recent version of jose, have checked their forums and find nothing.\n\nHere is my docker-compose:\n\n```\nservices:\n postgres:\n image: postgres\n restart: always\n environment:\n POSTGRES_USER: postgres\n POSTGRES_PASSWORD: postgres\n POSTGRES_DB: postgres\n ports:\n - 5432:5432\n volumes:\n - postgres-data:/var/lib/postgresql/data\n healthcheck:\n test: [\"CMD-SHELL\", \"sh -c 'pg_isready -U postgres -d postgres'\"]\n interval: 10s\n timeout: 3s\n retries: 3\n\n web:\n build:\n context: .\n args:\n - VERCEL_TOKEN=${VERCEL_TOKEN}\n volumes:\n - ./app:/app/app\n - ./prisma:/app/prisma\n - ./public:/app/public\n - ./swagger:/app/swagger\n ports:\n - 3000:3000\n - 5555:5555\n depends_on:\n - postgres\n\nvolumes:\n postgres-data:\n```\n\nHere is my Dockerfile:\n\n```\nFROM node:20\n\nWORKDIR /app\n\nCOPY package.json ./\n\nRUN npm install\n\nRUN npm install --global vercel@latest\n\nCOPY . .\n\nARG VERCEL_TOKEN\nRUN vercel env pull .env --environment=Development --token=$VERCEL_TOKEN\n\nRUN npx prisma generate --schema ./prisma/schema.prisma\n\nENV POSTGRES_DATABASE=postgres\nENV POSTGRES_USER=postgres\nENV POSTGRES_PASSWORD=postgres\nENV POSTGRES_HOST=postgres\nENV POSTGRES_URL=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_PRISMA_URL=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_URL_NON_POOLING=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_PORT=5432\n\nEXPOSE 3000\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\nI have found nothing online for this error, nobody ever seemed to have this issue. I purged all docker containers and ran docker system prune with a clean rebuild but no luck. I don't know what else to try here.\n\nEdit: my dockerignore:\n\n```\n**/node_modules\n.next\n.swc\n.env\n```\n\n========================================\n\nTop Answer:\nIf you are using your postinstall script to do `prisma generate`. You must make sure when building your image, the image has a copy of your prisma files\n\nExample, I often use the Dockerfile template provided by NextJS here:\n\nThus I added the following COPY command to ensure the Dockerimage has my prisma files.\n\n```\n# Template from https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile\n\nFROM node:18-alpine AS base\n\n# Install dependencies only when needed\nFROM base AS deps\n# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.\nRUN apk add --no-cache libc6-compat\nWORKDIR /app\n\n# Prisma files must be copied. Comment this line if prisma is not installed\nCOPY prisma/ /app/prisma/\n\n# Install dependencies based on the preferred package manager\nCOPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./\nRUN \\\n if [ -f yarn.lock ]; then yarn --frozen-lockfile; \\\n elif [ -f package-lock.json ]; then npm ci; \\\n elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \\\n else echo \"Lockfile not found.\" && exit 1; \\\n fi\n\n# Rebuild the source code only when needed\nFROM base AS builder\nWORKDIR /app\nCOPY --from=deps /app/node_modules ./node_modules\nCOPY . .\n\n# Next.js collects completely anonymous telemetry data about general usage.\n# Learn more here: https://nextjs.org/telemetry\n# Uncomment the following line in case you want to disable telemetry during the build.\n# ENV NEXT_TELEMETRY_DISABLED=1\n\nRUN \\\n if [ -f yarn.lock ]; then yarn run build; \\\n elif [ -f package-lock.json ]; then npm run build; \\\n elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \\\n else echo \"Lockfile not found.\" && exit 1; \\\n fi\n\n# Production image, copy all the files and run next\nFROM base AS runner\nWORKDIR /app\n\nENV NODE_ENV=production\n# Uncomment the following line in case you want to disable telemetry during runtime.\n# ENV NEXT_TELEMETRY_DISABLED=1\n\nRUN addgroup --system --gid 1001 nodejs\nRUN adduser --system --uid 1001 nextjs\n\nCOPY --from=builder /app/public ./public\n\n# Set the correct permission for prerender cache\nRUN mkdir .next\nRUN chown nextjs:nodejs .next\n\n# Automatically leverage output traces to reduce image size\n# https://nextjs.org/docs/advanced-features/output-file-tracing\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static\n\nUSER nextjs\n\nEXPOSE 3000\n\nENV PORT=3000\n\n# server.js is created by next build from the standalone output\n# https://nextjs.org/docs/pages/api-reference/next-config-js/output\nENV HOSTNAME=\"0.0.0.0\"\nCMD [\"node\", \"server.js\"]\n```\n\n========================================\n\nCode:\n```text\n90.79 > hey-shop@0.1.0 postinstall\n90.79 > prisma generate\n90.79 \n91.03 Error: Could not find Prisma Schema that is required for this command.\n91.03 You can either provide it with `--schema` argument, set it as `prisma.schema` in your package.json or put it into the default location.\n91.03 Checked following paths:\n91.03 \n91.03 schema.prisma: file not found\n91.03 prisma/schema.prisma: file not found\n91.03 prisma/schema: directory not found\n91.03 \n91.03 See also https://pris.ly/d/prisma-schema-location\n91.03 npm notice\n91.03 npm notice New minor version of npm available! 10.7.0 -> 10.8.1\n91.03 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.8.1\n91.03 npm notice To update run: npm install -g npm@10.8.1\n91.03 npm notice\n91.03 npm error code 1\n91.03 npm error path /app\n91.03 npm error command failed\n91.03 npm error command sh -c prisma generate\n91.04 \n91.04 npm error A complete log of this run can be found in: /root/.npm/_logs/2024-06-28T08_02_21_293Z-debug-0.log\n------\nfailed to solve: process \"/bin/sh -c npm install\" did not complete successfully: exit code: 1\n```\n\n```text\n\"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next-swagger-doc-cli next-swagger-doc.json && next build\",\n    \"start\": \"next start\",\n    \"lint\": \"next lint\",\n    \"resetdb\": \"cross-env NODE_ENV=test npx prisma db push --force-reset && npx prisma db seed\",\n    \"postinstall\": \"prisma generate\",\n    \"generate-docs\": \"next-swagger-doc-cli next-swagger-doc.json\",\n    \"test\": \"cross-env NODE_ENV=test jest\",\n    \"test:watch\": \"cross-env NODE_ENV=test jest --watch\"\n  },\n  \"prisma\": {\n    \"seed\": \"tsx prisma/seed.ts\"\n  },\n```\n\n```text\nweb-1       |  ○ Compiling / ...\nweb-1       |  ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1       | \nweb-1       | Import trace for requested module:\nweb-1       | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1       | ./node_modules/jose/dist/node/esm/index.js\nweb-1       | ./app/lib/auth.ts\nweb-1       | ./app/lib/utils/api-authorization.ts\nweb-1       | ./app/(general)/layout.tsx\nweb-1       |  ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1       | \nweb-1       | Import trace for requested module:\nweb-1       | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1       | ./node_modules/jose/dist/node/esm/index.js\nweb-1       | ./app/lib/auth.ts\nweb-1       | ./app/ui/search/pagination.tsx\nweb-1       | ./app/(general)/page.tsx\nweb-1       |  ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1       | \nweb-1       | Import trace for requested module:\nweb-1       | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1       | ./node_modules/jose/dist/node/esm/index.js\nweb-1       | ./app/lib/auth.ts\nweb-1       | ./app/ui/search/pagination.tsx\nweb-1       | ./app/(general)/page.tsx\nweb-1       |  ⨯ ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | Attempted import error: 'normalizePrivateKey' is not exported from '../runtime/normalize_key.js' (imported as 'normalize').\nweb-1       | \nweb-1       | Import trace for requested module:\nweb-1       | ./node_modules/jose/dist/node/esm/lib/decrypt_key_management.js\nweb-1       | ./node_modules/jose/dist/node/esm/jwe/flattened/decrypt.js\nweb-1       | ./node_modules/jose/dist/node/esm/index.js\nweb-1       | ./app/lib/auth.ts\nweb-1       | ./app/ui/search/pagination.tsx\nweb-1       | ./app/(general)/page.tsx\n```\n\n```text\nservices:\n  postgres:\n    image: postgres\n    restart: always\n    environment:\n      POSTGRES_USER: postgres\n      POSTGRES_PASSWORD: postgres\n      POSTGRES_DB: postgres\n    ports:\n      - 5432:5432\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    healthcheck:\n      test: [\"CMD-SHELL\", \"sh -c 'pg_isready -U postgres -d postgres'\"]\n      interval: 10s\n      timeout: 3s\n      retries: 3\n\n  web:\n    build:\n      context: .\n      args:\n        - VERCEL_TOKEN=${VERCEL_TOKEN}\n    volumes:\n      - ./app:/app/app\n      - ./prisma:/app/prisma\n      - ./public:/app/public\n      - ./swagger:/app/swagger\n    ports:\n      - 3000:3000\n      - 5555:5555\n    depends_on:\n      - postgres\n\nvolumes:\n  postgres-data:\n```\n\n```text\nFROM node:20\n\nWORKDIR /app\n\nCOPY package.json ./\n\nRUN npm install\n\nRUN npm install --global vercel@latest\n\nCOPY . .\n\nARG VERCEL_TOKEN\nRUN vercel env pull .env --environment=Development --token=$VERCEL_TOKEN\n\nRUN npx prisma generate --schema ./prisma/schema.prisma\n\nENV POSTGRES_DATABASE=postgres\nENV POSTGRES_USER=postgres\nENV POSTGRES_PASSWORD=postgres\nENV POSTGRES_HOST=postgres\nENV POSTGRES_URL=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_PRISMA_URL=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_URL_NON_POOLING=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_PORT=5432\n\nEXPOSE 3000\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```text\n**/node_modules\n.next\n.swc\n.env\n```\n\n```text\nFROM node:20\n\nWORKDIR /app\n\nCOPY package*.json ./\n\nRUN npm install\n\nRUN npm install --global vercel@latest\n\nCOPY . .\n\nARG VERCEL_TOKEN\nRUN vercel env pull .env --environment=Development --token=$VERCEL_TOKEN\n\nENV POSTGRES_DATABASE=postgres\nENV POSTGRES_USER=postgres\nENV POSTGRES_PASSWORD=postgres\nENV POSTGRES_HOST=postgres\nENV POSTGRES_URL=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_PRISMA_URL=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_URL_NON_POOLING=postgres://postgres:postgres@postgres:5432/postgres?connect_timeout=300&schema=public\nENV POSTGRES_PORT=5432\n\nEXPOSE 3000\n\nCMD [\"npm\", \"run\", \"dev\"]\n```\n\n```text\ndocker exec -it hey-shop-web-1 bash\n```\n\n```text\nnpm install\n```\n\n```text\ndocker-compose up\n```\n\n```text\ndocker-compose up --build\n```\n\n```text\nCOPY package.json ./\n```\n\n```text\nCOPY package*.json ./\n```\n\n```text\n**/node_modules\n```\n\n```text\n.dockerignore\n```\n\n```text\nnpm install\n```\n\n```text\nnpm install\n```\n\n```text\nnpm upgrade jose\n```\n\n```text\n# Template from https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile\n\n\nFROM node:18-alpine AS base\n\n# Install dependencies only when needed\nFROM base AS deps\n# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.\nRUN apk add --no-cache libc6-compat\nWORKDIR /app\n\n# Prisma files must be copied. Comment this line if prisma is not installed\nCOPY prisma/ /app/prisma/\n\n# Install dependencies based on the preferred package manager\nCOPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./\nRUN \\\n  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \\\n  elif [ -f package-lock.json ]; then npm ci; \\\n  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \\\n  else echo \"Lockfile not found.\" && exit 1; \\\n  fi\n\n\n# Rebuild the source code only when needed\nFROM base AS builder\nWORKDIR /app\nCOPY --from=deps /app/node_modules ./node_modules\nCOPY . .\n\n# Next.js collects completely anonymous telemetry data about general usage.\n# Learn more here: https://nextjs.org/telemetry\n# Uncomment the following line in case you want to disable telemetry during the build.\n# ENV NEXT_TELEMETRY_DISABLED=1\n\nRUN \\\n  if [ -f yarn.lock ]; then yarn run build; \\\n  elif [ -f package-lock.json ]; then npm run build; \\\n  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \\\n  else echo \"Lockfile not found.\" && exit 1; \\\n  fi\n\n# Production image, copy all the files and run next\nFROM base AS runner\nWORKDIR /app\n\nENV NODE_ENV=production\n# Uncomment the following line in case you want to disable telemetry during runtime.\n# ENV NEXT_TELEMETRY_DISABLED=1\n\nRUN addgroup --system --gid 1001 nodejs\nRUN adduser --system --uid 1001 nextjs\n\nCOPY --from=builder /app/public ./public\n\n# Set the correct permission for prerender cache\nRUN mkdir .next\nRUN chown nextjs:nodejs .next\n\n# Automatically leverage output traces to reduce image size\n# https://nextjs.org/docs/advanced-features/output-file-tracing\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static\n\nUSER nextjs\n\nEXPOSE 3000\n\nENV PORT=3000\n\n# server.js is created by next build from the standalone output\n# https://nextjs.org/docs/pages/api-reference/next-config-js/output\nENV HOSTNAME=\"0.0.0.0\"\nCMD [\"node\", \"server.js\"]\n```\n\n```text\nprisma generate\n```\n\n========================================\n\nComments:\n- Are you seeing these errors when you're building the image or running the container? It looks like the first error might be coming from your `postinstall` hook, so you might need to `COPY` the schema file into the image before you `RUN npm install`. The `volumes:` block means you aren't actually running any of the code in your image, which can result in unpredictable behavior depending on what's on the host system; does deleting that entire block make any difference?\n- @DavidMaze I see these errors when I run `docker-compose up --build`. I also think that the first error comes from the postinstall script, although I thought that the schema was available and didn't need to be copied as I added the prisma folder to the volumes block. And what do you mean with the volumes block causing my code not to run anything in the image? I added these volumes to have them in sync with the container when I write code.\n- Jose is already on the most recent version\n- Which is why you're not getting the error as per your own answer.\n- As you can see in my original question, I have added the prisma folder as a volume. Thus docker has access to it.","metadata":{"transformedAt":"2026-08-18T18:33:14.849Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":619,"estimatedTokens":4979}}307{"id":"stack-54203167","source":"stackoverflow","questionId":54203167,"title":"GraphQL/Prisma Client Server Error: Variable '$data' cannot be non input type 'LinkCreateInput!'. (line 1, column 18)","tags":["node.js","server","graphql","prisma","prisma-graphql"],"text":"Title: GraphQL/Prisma Client Server Error: Variable '$data' cannot be non input type 'LinkCreateInput!'. (line 1, column 18)\nTags: node.js, server, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am following the How To GraphQL Node.js tutorial and I am at the part \"Connecting Server and Database with Prisma Bindings\". I think I have everything set up correctly according to the tutorial but when I try to execute a post mutation in the GraphQL Playground it throws this error: \n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Variable '$data' cannot be non input type 'LinkCreateInput!'. (line 1, column 18):\\nmutation ($data: LinkCreateInput!) {\\n ^\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"post\"\n ]\n }\n ]\n}\n```\n\nI'm not even sure what I should be getting back, but when I do the \"info\" query I get back the info from my index.js file: \"data\": {\n \"info\": \"This is the API for the Hacker News clone!, Get Rigth Witcha, imma get ya !!\"\n }\n\nSo, I know that the info query is working. When I try to do the Feed query I get back this error in the GraphQl playground:\n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot query field 'links' on type 'Query'. (line 2, column 3):\\n links {\\n ^\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"feed\"\n ]\n }\n ]\n}\n```\n\nSo only the Info query is working and the others keep sending back an error. I am so lost and I really want to get more skill with GRaohQL. When I go to my Prisma Client I can't access my Service. They only let me look at the list of my servers. I have screenshots of the console but I do not have enough reputation to post them with this question. \n\nI have tried going over each step and making sure my code is correct. I've also checked out the HowToGraphql git repository however they only have the completed server code present and I would like to build mine from the ground up so their code isn't much help. I'm not sure if the problem is with the Prisma Client or my code. Any feedback or assistance would be greatly appreciated!!\n\nHere is the link to the repository: \nhttps://github.com/thelovesmith/HckrNws-Cln-GrphQL-Srvr\n\nPlease help!!\n\nsrc/index.js:\n\n```\nconst { GraphQLServer } = require('graphql-yoga')\nconst { prisma } = require('./generated/prisma-client/index')\n// Revolvers\nconst resolvers = {\n Query: {\n info: () => 'This is the API for the Hacker News clone!, \nGet Rigth Witcha, imma get ya !!' ,\n feed: (root, args, context, info) => {\n return context.prisma.links()\n }\n },\n Mutation: {\n post : (root, args, context) => {\n return context.prisma.createLink({\n url: args.url,\n description: args.description,\n })\n }\n },\n}\n//Server\nconst server = new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n //initializing context object that is being passed to each \nresolver \n context: { prisma },\n})\nserver.start(() => console.log('Server is running on \nhttp://localhost:4000'))\n```\n\nschema.graphql:\n\n```\ntype Query {\n info: String!\n feed: [Link!]!\n}\n\ntype Mutation {\n post(url: String!, description: String!): Link!\n}\n\ntype Link {\n id: ID!\n description: String!\n url: String!\n}\n```\n\nprisma.yml:\n\n```\n# The HTTP endpoint for your Prisma API\n#endpoint: ''\nendpoint: https://us1.prisma.sh/avery-dante-hinds/hckrnws/dev\n\n# Points to the file that contains your datamodel\ndatamodel: datamodel.prisma\n\n# Specifies language & location for the generated Prisma client\ngenerate:\n - generator: javascript-client\n output: ../src/generated/prisma-client\n```\n\ndatamodel.prisma:\n\n```\ntype Link { \n id: ID! @ unique\n createdAt: DateTime!\n description: String!\n url: String!\n}\n```\n\n### UPDATE\n\nWhen I run Prisma Deploy I can an error message:\n\n```\nERROR: Syntax error while parsing GraphQL query. Invalid input \"{ \n \\n id: ID! @ \", expected ImplementsInterfaces, DirectivesConst or \nFieldDefinitions (line 1, column 11):\ntype Link {\n ^\n\n{\n \"data\": {\n \"deploy\": null\n },\n \"errors\": [\n {\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 9\n }\n ],\n \"path\": [\n \"deploy\"\n ],\n \"code\": 3017,\n \"message\": \"Syntax error while parsing GraphQL query. Invalid \ninput \\\"{ \\\\n id: ID! @ \\\", expected ImplementsInterfaces, \nDirectivesConst or FieldDefinitions (line 1, column 11):\\ntype Link { \n\\n ^\",\n \"requestId\": \"us1:cjr0vodzl2ykt0a71zuql5544\"\n }\n ],\n \"status\": 200\n}\n```\n\n========================================\n\nCode:\n```text\n{\n  \"data\": null,\n  \"errors\": [\n    {\n      \"message\": \"Variable '$data' cannot be non input type 'LinkCreateInput!'. (line 1, column 18):\\nmutation ($data: LinkCreateInput!) {\\n                 ^\",\n      \"locations\": [\n        {\n          \"line\": 2,\n          \"column\": 3\n        }\n      ],\n      \"path\": [\n        \"post\"\n      ]\n    }\n  ]\n}\n```\n\n```text\n{\n  \"data\": null,\n  \"errors\": [\n    {\n      \"message\": \"Cannot query field 'links' on type 'Query'. (line 2, column 3):\\n  links {\\n  ^\",\n      \"locations\": [\n        {\n          \"line\": 2,\n          \"column\": 3\n        }\n      ],\n      \"path\": [\n        \"feed\"\n      ]\n    }\n  ]\n}\n```\n\n```text\nconst { GraphQLServer } = require('graphql-yoga')\nconst { prisma } = require('./generated/prisma-client/index')\n// Revolvers\nconst resolvers = {\n    Query: {\n        info: () =>  'This is the API for the Hacker News clone!, \nGet Rigth Witcha, imma get ya !!' ,\n        feed: (root, args, context, info) => {\n            return context.prisma.links()\n        }\n    },\n    Mutation: {\n        post : (root, args, context) => {\n            return context.prisma.createLink({\n                url: args.url,\n                description: args.description,\n            })\n        }\n    },\n}\n//Server\nconst server = new GraphQLServer({\n    typeDefs: './src/schema.graphql',\n    resolvers,\n    //initializing context object that is being passed to each \nresolver \n    context: { prisma },\n})\nserver.start(() => console.log('Server is running  on \nhttp://localhost:4000'))\n```\n\n```text\ntype Query {\n  info: String!\n  feed: [Link!]!\n}\n\ntype Mutation {\n  post(url: String!, description: String!): Link!\n}\n\ntype Link {\n  id: ID!\n  description: String!\n  url: String!\n}\n```\n\n```text\n# The HTTP endpoint for your Prisma API\n#endpoint: ''\nendpoint: https://us1.prisma.sh/avery-dante-hinds/hckrnws/dev\n\n# Points to the file that contains your datamodel\ndatamodel: datamodel.prisma\n\n# Specifies language & location for the generated Prisma client\ngenerate:\n  - generator: javascript-client\n    output: ../src/generated/prisma-client\n```\n\n```text\ntype Link { \n    id: ID! @ unique\n    createdAt: DateTime!\n    description: String!\n    url: String!\n}\n```\n\n```text\nERROR: Syntax error while parsing GraphQL query. Invalid input \"{ \n \\n    id: ID! @ \", expected ImplementsInterfaces, DirectivesConst or \nFieldDefinitions (line 1, column 11):\ntype Link {\n      ^\n\n{\n  \"data\": {\n    \"deploy\": null\n  },\n  \"errors\": [\n    {\n      \"locations\": [\n        {\n          \"line\": 2,\n          \"column\": 9\n        }\n      ],\n      \"path\": [\n        \"deploy\"\n      ],\n      \"code\": 3017,\n      \"message\": \"Syntax error while parsing GraphQL query. Invalid \ninput \\\"{ \\\\n    id: ID! @ \\\", expected ImplementsInterfaces, \nDirectivesConst or FieldDefinitions (line 1, column 11):\\ntype Link { \n\\n          ^\",\n      \"requestId\": \"us1:cjr0vodzl2ykt0a71zuql5544\"\n    }\n  ],\n \"status\": 200\n}\n```\n\n```text\n@unique\n```\n\n```text\n@ unique\n```\n\n========================================\n\nComments:\n- Hey, I was just checking your project. It seems like there's a problem with your Prisma API. Did you run `prisma deploy` successfully?\n- Otherwise the code looks good 👍\n- @nburk HEy thank you! Originally when I ran prisma deploy it went through fine , but I just ran it again and got an error message\n- Can you post the error please?\n- @nburk I added it to the end of the question above. Under the Update subtitle. I realy appreciate your help\n- It seems like there's an issue with the `@unique` directive in your datamodel. There's a *space* between the `@` and `unique` that should not be there. Try to fix that and deploy again.\n- This is where the issue is: github.com/thelovesmith/HckrNws-Cln-GrphQL-Srvr/blob/master/&zwnj;&#8203;&hellip;\n- oh wow smh such a silly mistake on my part. But yes It is working now and I have Prisma Deployed. Thank you @nburk !!!!","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":350,"estimatedTokens":2056}}308{"id":"stack-78112338","source":"stackoverflow","questionId":78112338,"title":"How to run prisma migrations when creating a docker container file?","tags":["docker","docker-compose","prisma","next.js13"],"text":"Title: How to run prisma migrations when creating a docker container file?\nTags: docker, docker-compose, prisma, next.js13\nSource: Stack Overflow\n\nQuestion:\nI have a nextjs app that uses prisma with a mysql database. I can succesfully create the containers and get the app working, but i must go in the docker terminal and manually run\n\n```\nnpx prisma migrate dev\n```\n\n.If i don't, they give me error because the tables don't exist in the database. How can i run this command automatically when i run docker-compose up --build -d ?\n\nHere is my Dockerfile\n\n```\nFROM node:18\n\nRUN apt-get update && apt-get install gnupg wget -y && \\\n wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \\\n sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list' && \\\n apt-get update && \\\n apt-get install google-chrome-stable -y --no-install-recommends && \\\n rm -rf /var/lib/apt/lists/*\n\nWORKDIR /app\n\nCOPY package*.json ./\n\nRUN npm install\n\nCOPY . .\n\nRUN npm run build\n\nRUN npx prisma generate\n\nEXPOSE 3000\n\nCMD [\"npm\", \"run\", \"dev\"]\n\n#RUN npx prisma migrate dev\n```\n\n========================================\n\nCode:\n```text\nnpx prisma migrate dev\n```\n\n```text\nFROM node:18\n\nRUN apt-get update && apt-get install gnupg wget -y && \\\n    wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \\\n    sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list' && \\\n    apt-get update && \\\n    apt-get install google-chrome-stable -y --no-install-recommends && \\\n    rm -rf /var/lib/apt/lists/*\n\nWORKDIR /app\n\n\nCOPY package*.json ./\n\nRUN npm install\n\nCOPY . .\n\n\nRUN npm run build\n\n\nRUN npx prisma generate\n\n\n\nEXPOSE 3000\n\n\nCMD [\"npm\", \"run\", \"dev\"]\n\n#RUN npx prisma migrate dev\n```\n\n```text\n#!/bin/bash\n\n# Apply migrations\nnpx prisma migrate dev\n\nexec \"$@\"\n```\n\n```text\nFROM node:18\nRUN apt-get update && apt-get install gnupg wget -y && \\\n    wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \\\n    sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list' && \\\n    apt-get update && \\\n    apt-get install google-chrome-stable -y --no-install-recommends && \\\n    rm -rf /var/lib/apt/lists/*\n\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCOPY . .\nRUN npm run build\nRUN npx prisma generate\nEXPOSE 3000\n\nCMD [\"npm\", \"run\", \"dev\"]\n\nCOPY ./docker-entrypoint.sh /docker-entrypoint.sh\nENTRYPOINT [\"/docker-entrypoint.sh\"]\n```\n\n```text\ndocker-entrypoint.sh\n```\n\n```text\nENTRYPOINT\n```\n\n========================================\n\nComments:\n- Consider making the last command in the entrypoint wrapper script `exec \"$@\"`, and adding back a default Dockerfile `CMD [\"npm\", \"run\", \"dev\"]` as in the original question. If you need to have the container do something else, `docker-compose run myapp bash`, it will still run migrations before running the alternate command.","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":130,"estimatedTokens":807}}309{"id":"stack-74188768","source":"stackoverflow","questionId":74188768,"title":"Advantage of using connect over updating foreign keys directly","tags":["prisma"],"text":"Title: Advantage of using connect over updating foreign keys directly\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nWhy use connect?\n\n```\ndata:{\n 'userId': 1\n}\n```\n\nthe above one is not enough??\n\nWhy use\n\n```\nuser:{\n connect:{\n id: 1\n }\n}\n```\n\nIsn't the result the same? I wonder\n\n========================================\n\nCode:\n```text\ndata:{\n  'userId': 1\n}\n```\n\n```text\nuser:{\n connect:{\n    id: 1\n  }\n}\n```\n\n```text\nconnect\n```\n\n```text\nconnect\n```\n\n```text\ndisconnect\n```\n\n```text\nconnectOrCreate\n```\n\n========================================\n\nComments:\n- Both should be valid. Are you experiencing issues?\n- @some-user I don`t have a issue but Then why does connect exist? (disconnect also) I`m confused . Does it exist because of readability?","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":65,"estimatedTokens":188}}310{"id":"stack-49739658","source":"stackoverflow","questionId":49739658,"title":"What is the best approach to handle file upload in graphql?","tags":["file-upload","graphql","prisma"],"text":"Title: What is the best approach to handle file upload in graphql?\nTags: file-upload, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a way to handle file upload in my backend powered by prisma (graphcool). However I am a beginner and it looks very intimidating and I don't know anything about how file upload works. What is the best aproach to do this ? Can I do it using prisma ? I have red about Amazon S3 buckets but it looks like a complicated approach to begin with.\n\n========================================\n\nCode:\n```text\napollo-upload-server\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":13,"estimatedTokens":143}}311{"id":"stack-73250615","source":"stackoverflow","questionId":73250615,"title":"Copying database record with it's relations in prisma","tags":["mysql","node.js","crud","prisma"],"text":"Title: Copying database record with it's relations in prisma\nTags: mysql, node.js, crud, prisma\nSource: Stack Overflow\n\nQuestion:\nMy system works on Node.JS with Prisma connected to mysql.\n\nLet's say I have two tables in my database: `house [ID|house_name]` and `resident [ID|name|house_ID]`. One house can be referenced by many residents (one-to-many relation). I want to copy one house with it's residents (creating a new record for each resident). I'm taking data from the house, including it's residents, then posting new house. Now I want to post all residents but with their house reference ID changed. The easiest way to do it would be, I think, to iterate through each resident that reference copied house and change their house_ID to... what exactly? How do I get ID of a new house when it's auto increment on database side? I can't find the correct record of a house using name as it's not unique. Also I can't depend on taking last record as there can be writes to the DB between write and read.\n\nExample code:\n\n```\nconst prisma = require(\"../prisma\");\n\nexports.copyHouse = async (req, res) => {\n\n let house = await prisma.House.findUnique({\n where: {\n id: +req.body.houseId\n },\n include: {\n residents: true,\n }\n });\n\n let newHouseData = {\n name: req.body.name,\n };\n\n residents = house.residents;\n\n await prisma.House.create({\n data: newHouseData\n });\n\n if (residents !== null) {\n for (let i = 0; i What would be the smartest way to approach this problem?\n\n========================================\n\nCode:\n```text\nconst prisma = require(\"../prisma\");\n\nexports.copyHouse = async (req, res) => {\n\n    let house = await prisma.House.findUnique({\n        where: {\n            id: +req.body.houseId\n        },\n        include: {\n            residents: true,\n        }\n    });\n\n    let newHouseData = {\n        name: req.body.name,\n    };\n\n    residents = house.residents;\n\n    await prisma.House.create({\n        data: newHouseData\n    });\n\n    if (residents !== null) {\n        for (let i = 0; i < residents.length; i++) {\n\n            residents[i].houseId = //what to put here????\n\n            await prisma.Resident.create({\n                data: residents[i]\n            });\n        }\n    }\n\n    res.status(200).json({ messages: [\n        {\n            message: 'House copied successfully',\n            type: 'success'\n        }\n    ]});\n};\n```\n\n```text\nhouse [ID|house_name]\n```\n\n```text\nresident [ID|name|house_ID]\n```\n\n```text\nlet newHouseDb = await prisma.House.create({\n        data: newHouseData\n    });\n\n    if (residents !== null) {\n        for (let i = 0; i < residents.length; i++) {\n\n            residents[i].houseId = newHouseDb.id;\n\n            await prisma.Resident.create({\n                data: residents[i]\n            });\n        }\n    }\n```\n\n```text\nawait prisma.House.create\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":113,"estimatedTokens":702}}312{"id":"stack-72826604","source":"stackoverflow","questionId":72826604,"title":"Prisma 2 - Unkown arg 'where' in select.fruit.where for type UserFruit. Did you mean 'select'? Available args","tags":["json","prisma","prisma2"],"text":"Title: Prisma 2 - Unkown arg 'where' in select.fruit.where for type UserFruit. Did you mean 'select'? Available args\nTags: json, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nTrying to query in prisma and filter results from a related object but get the error:\n\nUnknown arg 'where' in select.fruit.where for type UserFruit. Did you\nmean 'select'? Available args fruit{}\n\n```\nasync findShops(req) {\n const userId = parseInt(req.params.id);\n const shop = await prisma.shop.findMany({\n select: {\n id: true,\n name: true,\n logo: true,\n fruit:{\n select:{\n id:true,\n userId:true,\n fruitNumber:true,\n created: true,\n updated: true,\n },\n where: {\n userId: userId\n }\n }\n }\n \n })\n return shop;\n };\n```\n\nexample payload expected:\n\n```\n[\n { id: 1001, name: 'test1', logo: 'log.png', fruit: null },\n { id: 1002, name: 'test2', logo: 'log2.jpg', fruit: null },\n { id: 1003, name: 'test3', logo: 'log3.jpg', fruit: null },\n {\n id: 1005,\n name: 'test4',\n logo: 'log4.png',\n fruit: {\n id: '62450ee5-e75d-4a67-8d79-120d11ddf508',\n userId: 111,\n fruitNumber: '123456',\n created: 2022-07-01T06:39:52.924Z,\n updated: 2022-07-01T06:39:52.936Z\n }\n },\n {\n id: 1004,\n name: 'test5',\n logo: 'log5.jpg',\n fruit: {\n id: '20e9af37-2e6f-4070-8475-c5a914f311dc',\n userId: 111,\n fruitNumber: '123878',\n created: 2022-07-01T07:21:27.898Z,\n updated: 2022-07-01T07:21:27.901Z\n }\n }\n]\n```\n\nI can easily achieve the expected output by not having the \"where\" but I need it because the fruit object can contain more than 1 object so I need to filter by userId e.g.\n\n```\nfruit: {\n id: '62450ee5-e75d-4a67-8d79-120d11ddf508',\n userId: 111,\n fruitNumber: '123456',\n created: 2022-07-01T06:39:52.924Z,\n updated: 2022-07-01T06:39:52.936Z\n },\n {\n id: '62450ee5-e75d-4a67-8d79-120d11ddf508',\n userId: 999,\n fruitNumber: '123456',\n created: 2022-07-01T06:39:52.924Z,\n updated: 2022-07-01T06:39:52.936Z\n }\n```\n\nFor the fruit object I need nulls and anything that matches the userId and based on design it should only ever be 1 record for each shop for the specific user.\n\nAt somepoint my code seemed to work but after I did a prisma generate it stopped working. Is there another way I can achieve the same result or is there someway to fix this?\n\nNote:version info below.\n\nhttps://i.sstatic.net/QoQwV.png\n\n```\nmodel UserFruit {\n id String @id @default(uuid())\n fruitNumber String @map(\"fruit_number\")\n shopId Int @unique @map(\"shop_id\")\n userId Int @map(\"user_id\")\n created DateTime @default(now())\n updated DateTime @updatedAt\n fruit Fruit @relation(fields: [fruitId], references: [id])\n\n @@unique([userId, fruitId], name: \"userFruit\")\n @@map(\"user_Fruit\")\n}\n\nmodel Shop {\n id Int @id @default(autoincrement())\n name String @unique\n logo String\n created DateTime @default(now())\n updated DateTime @updatedAt\n fruit UserFruit?\n\n @@map(\"Shop\")\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n created DateTime @default(now())\n updated DateTime @updatedAt\n uid String @unique\n email String @unique\n phone String @unique\n firstName String @map(\"first_name\")\n lastName String @map(\"last_name\")\n dob DateTime?\n gender String?\n roleId Int @default(1) @map(\"role_id\")\n role Role @relation(fields: [roleId], references: [id])\n\n @@map(\"user\")\n}\n```\n\n========================================\n\nCode:\n```text\nasync findShops(req) {\n        const userId = parseInt(req.params.id);\n        const shop = await prisma.shop.findMany({\n            select: {\n              id: true,\n              name: true,\n              logo: true,\n              fruit:{\n                select:{\n                  id:true,\n                  userId:true,\n                  fruitNumber:true,\n                  created: true,\n                  updated: true,\n                },\n                where: {\n                  userId: userId\n                }\n              }\n            }\n            \n          })\n        return shop;\n    };\n```\n\n```text\n[\n  { id: 1001, name: 'test1', logo: 'log.png', fruit: null },\n  { id: 1002, name: 'test2', logo: 'log2.jpg', fruit: null },\n  { id: 1003, name: 'test3', logo: 'log3.jpg', fruit: null },\n  {\n    id: 1005,\n    name: 'test4',\n    logo: 'log4.png',\n    fruit: {\n      id: '62450ee5-e75d-4a67-8d79-120d11ddf508',\n      userId: 111,\n      fruitNumber: '123456',\n      created: 2022-07-01T06:39:52.924Z,\n      updated: 2022-07-01T06:39:52.936Z\n    }\n  },\n  {\n    id: 1004,\n    name: 'test5',\n    logo: 'log5.jpg',\n    fruit: {\n      id: '20e9af37-2e6f-4070-8475-c5a914f311dc',\n      userId: 111,\n      fruitNumber: '123878',\n      created: 2022-07-01T07:21:27.898Z,\n      updated: 2022-07-01T07:21:27.901Z\n    }\n  }\n]\n```\n\n```text\nfruit: {\n          id: '62450ee5-e75d-4a67-8d79-120d11ddf508',\n          userId: 111,\n          fruitNumber: '123456',\n          created: 2022-07-01T06:39:52.924Z,\n          updated: 2022-07-01T06:39:52.936Z\n        },\n        {\n          id: '62450ee5-e75d-4a67-8d79-120d11ddf508',\n          userId: 999,\n          fruitNumber: '123456',\n          created: 2022-07-01T06:39:52.924Z,\n          updated: 2022-07-01T06:39:52.936Z\n        }\n```\n\n```text\nmodel UserFruit {\n  id         String   @id @default(uuid())\n  fruitNumber String   @map(\"fruit_number\")\n  shopId  Int      @unique @map(\"shop_id\")\n  userId     Int      @map(\"user_id\")\n  created    DateTime @default(now())\n  updated    DateTime @updatedAt\n  fruit    Fruit  @relation(fields: [fruitId], references: [id])\n\n  @@unique([userId, fruitId], name: \"userFruit\")\n  @@map(\"user_Fruit\")\n}\n\nmodel Shop {\n  id      Int       @id @default(autoincrement())\n  name    String    @unique\n  logo    String\n  created DateTime  @default(now())\n  updated DateTime  @updatedAt\n  fruit    UserFruit?\n\n  @@map(\"Shop\")\n}\n\nmodel User {\n  id        Int       @id @default(autoincrement())\n  created   DateTime  @default(now())\n  updated   DateTime  @updatedAt\n  uid       String    @unique\n  email     String    @unique\n  phone     String    @unique\n  firstName String    @map(\"first_name\")\n  lastName  String    @map(\"last_name\")\n  dob       DateTime?\n  gender    String?\n  roleId    Int       @default(1) @map(\"role_id\")\n  role      Role      @relation(fields: [roleId], references: [id])\n\n  @@map(\"user\")\n}\n```\n\n```js\nconst userId = parseInt(req.params.id);\nconst shop = await prisma.shop.findMany({\n  select: {\n    id: true,\n    name: true,\n    logo: true,\n    fruit: {\n      select: {\n        id: true,\n        userId: true,\n        fruitNumber: true,\n        created: true,\n        updated: true,\n      },\n      // Removed the nested \"where\" from here\n    },\n  },\n  where: {\n    // One of the following conditions must be true\n    OR: [\n      // Return shops who have a connected fruit AND\n      // the fruit's \"userId\" attribute equals the variable \"userID\"\n      {\n        fruit: {\n          is: {\n            userId: userId,\n            // Can also simplify this to the below line if you want\n            // userId\n          },\n        },\n      },\n      // Return shops who do not have a connected fruit\n      // this will be true if \"fruitId\" is null\n      // could also write this as {fruit: {is: {}}}\n      {\n        fruitId: {\n          equals: null,\n        },\n      },\n    ],\n  },\n});\n```\n\n```text\nwhere\n```\n\n```text\nuserId\n```\n\n```text\nselect\n```\n\n```text\nfruit\n```\n\n```text\nuserId\n```\n\n```text\nuserId\n```\n\n========================================\n\nComments:\n- You don't seem to be including any fruit relation inside your query. Is it supposed to be `fruit` instead of `card`? Could you kindly the relevant portion of your Prisma schema as well?\n- Thanks for picking that up, it was a typo in the question. In the code I actually had `fruit` so the issue still remains. I've attached the relevant schema.\n- Your schema does not seem to be functional (there's a missing fruit model and the `UserFruit` relation on `Shop` is not defined on the `UserFruit` side), so I can't reproduce the problem. In general though, what you're trying to do should work fine. Also, you mentioned that there can be multiple instances of `fruit`, but this is not possible as each `Shop` can only have one `fruit` record related to it.\n- Figuring out the correct schema and query would be ideal, but since I can't replicate it at the moment, a more simple/trivial solutio would be to `include` fruit without the `where` condition, and then use javascript `filter` to simply remove entities that do not match the condition. Basically take the where condition to your application code.\n- `UserFruit` is the fruit model, the key/reference is `shop_id` and `user_id` in `UserFruit` that ties to the other. If I was to filter it via javascript i don't need the `include` because I am already getting the full array.\n- Can you please post your `Fruit` model? And the `findShops` calling code.\n- @shmuels as mentioned in previous comment `UserFruit` is the `Fruit` model and `findShops` calling code is in the first code block in the description.\n- The problem is I also want the shops where `fruit` object is `null` in addition to where if it's not null its equal to `userId` can I do an OR statement as well?\n- @TEZZ I've edited my original answer, you can do `OR` to check that *either* the connected fruit matches `userId` *OR* there is no connected fruit iat all\n- Thanks, I realised that I needed to convert the `fruit` object to a List/Array as the data type and then I used your code with a bit of a tweek. `is` I used `some`, `equals` I used `every` otherwise it pops up with an error.","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":345,"estimatedTokens":2356}}313{"id":"stack-67992416","source":"stackoverflow","questionId":67992416,"title":"How can I use createMany with foreign keys in prisma?","tags":["postgresql","graphql","apollo","prisma"],"text":"Title: How can I use createMany with foreign keys in prisma?\nTags: postgresql, graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in using Prisma and am stuck at trying to figure out how to initially load data into postgres tables. I have tried seeding my db as per this example in prisma\nhttps://github.com/prisma/prisma-examples/tree/latest/javascript/graphql-auth\nbut it seems the main() is not getting triggered by the command \"npx prisma db seed --preview-feature\".\nSo I tried to insert into my db through a temporary function but I am getting an invalid invocation error on starting dev server:\n\n`Foreign key constraint failed on the field: Animals_categoryName_fkey (index)`\n\nBut I am not getting this error when I don't use foreign keys. Below is my schema.prisma, types and the data that I need to add.\n\nSchema.prisma\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Animals{\n id Int @id @default(autoincrement())\n image String\n price String\n description String[]\n stock Int\n onSale Boolean\n title String\n category Category @relation(fields: [categoryName], references: [categoryName])\n slug String @unique\n categoryName String\n}\n\nmodel Category{\n id Int @id @default(autoincrement())\n image String\n categoryName String @unique\n animals Animals[]\n}\n\nmodel MainCards{\n cardId Int @id @default(autoincrement())\n image String\n title String\n}\n```\n\ntypedefs--\n\n```\nconst typeDefs = gql`\n type MainCard {\n title: String!\n image: String!\n }\n \n type Animals{\n id: ID!\n image: String!\n price: String!\n description: [String!]!\n stock: Int!\n onSale: Boolean\n slug: String\n categoryName: String\n title: String\n }\n \n type Category{\n id: ID!\n image: String!\n categoryName: String!\n }\n \n type Query {\n mainCards: [MainCard]\n animals: [Animals]\n animal(slug: String!): Animals\n categories: [Category]\n category(categoryName: String!): [Animals]\n }\n `;\n```\n\nPart of data to add:\n\n```\nconst AnimalsData = async () => {\n await prisma.animals.createMany({\n data: [\n {\n image: \"lion\",\n title: \"7-year Male Lion with Large Well Kept Main with a Beautiful Yellow/Brownish Color\",\n price: \"23,322\",\n description: [\n \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\",\n \"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n \"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\",\n \"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n ],\n stock: 14,\n onSale: false,\n slug: \"lion\",\n categoryName: \"cats\"\n }, \n {\n image: \"gorilla\",\n title: \"Black Haired Gorilla with Broad Chest and Shoulder. Would be an Excellent Spot at the Gym\",\n price: \"47,775\",\n description: [\n \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\",\n \"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n \"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\",\n \"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n ],\n stock: 14,\n onSale: false,\n slug: \"gorilla\",\n categoryName: \"mammals\"\n } \n ]\n })\n}\n\nAnimalsData()\n.catch(e => {throw e})\n.finally(async () => {await prisma.$disconnect()})\n```\n\nIf it helps in any way, I am using prisma 2.24, apollo and graphql with a postgres database.\nAny help or suggestion is greatly appreciated.\n\n========================================\n\nCode:\n```text\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel Animals{\n  id Int @id @default(autoincrement())\n  image String\n  price String\n  description String[]\n  stock Int\n  onSale Boolean\n  title String\n  category Category @relation(fields: [categoryName], references: [categoryName])\n  slug String @unique\n  categoryName String\n}\n\nmodel Category{\n  id Int @id @default(autoincrement())\n  image String\n  categoryName String @unique\n  animals Animals[]\n}\n\nmodel MainCards{\n  cardId Int @id @default(autoincrement())\n  image String\n  title String\n}\n```\n\n```text\nconst typeDefs = gql`\n      type MainCard {\n          title: String!\n          image: String!\n      }\n    \n      type Animals{\n        id: ID!\n        image: String!\n        price: String!\n        description: [String!]!\n        stock: Int!\n        onSale: Boolean\n        slug: String\n        categoryName: String\n        title: String\n      }\n    \n      type Category{\n        id: ID!\n        image: String!\n        categoryName: String!\n      }\n    \n      type Query {\n        mainCards: [MainCard]\n        animals: [Animals]\n        animal(slug: String!): Animals\n        categories: [Category]\n        category(categoryName: String!): [Animals]\n      }\n    `;\n```\n\n```text\nconst AnimalsData = async () => {\n    await prisma.animals.createMany({\n        data: [\n            {\n                image: \"lion\",\n                title: \"7-year Male Lion with Large Well Kept Main with a Beautiful Yellow/Brownish Color\",\n                price: \"23,322\",\n                description: [\n                    \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\",\n                    \"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n                    \"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\",\n                    \"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n                ],\n                stock: 14,\n                onSale: false,\n                slug: \"lion\",\n                categoryName: \"cats\"\n            },            \n            {\n                image: \"gorilla\",\n                title: \"Black Haired Gorilla with Broad Chest and Shoulder. Would be an Excellent Spot at the Gym\",\n                price: \"47,775\",\n                description: [\n                    \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\",\n                    \"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\",\n                    \"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\",\n                    \"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n                ],\n                stock: 14,\n                onSale: false,\n                slug: \"gorilla\",\n                categoryName: \"mammals\"\n            }            \n        ]\n    })\n}\n\nAnimalsData()\n.catch(e => {throw e})\n.finally(async () => {await prisma.$disconnect()})\n```\n\n```text\nForeign key constraint failed on the field: Animals_categoryName_fkey (index)\n```\n\n```js\nawait prisma.category.createMany({\n        data: [\n            {\n                categoryName: \"mammals\",\n                image: \"__PLACEHOLDER_VALUE__\"  // change appropriately\n            },\n            {\n                categoryName: \"cats\",\n                image: \"__PLACEHOLDER_VALUE__\"  // change appropriately\n            }\n        ]\n    })\n\n//  ...run await prisma.animals.createMany\n```\n\n```text\nAnimal\n```\n\n```text\nAnimals.categoryName\n```\n\n```text\ncategoryName\n```\n\n```text\nCategory\n```\n\n```text\nCategory\n```\n\n```text\ncategoryName\n```\n\n```text\nAnimals\n```\n\n```text\nCategory\n```\n\n```text\nCategory.categoryName\n```\n\n```text\nanimals.createMany\n```\n\n```text\nAnimal\n```\n\n```text\nCategory\n```\n\n```text\ncreateMany\n```\n\n```text\ncreate\n```\n\n```text\ncreateMany\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.850Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":336,"estimatedTokens":1997}}314{"id":"stack-72228277","source":"stackoverflow","questionId":72228277,"title":"Is it possible to make a join query with Prisma without a foreign key?","tags":["mysql","next.js","prisma","prisma-graphql","prisma2"],"text":"Title: Is it possible to make a join query with Prisma without a foreign key?\nTags: mysql, next.js, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nI've been struggling with this for a while but with no success.\n\nI have two tables that **might** have a relation but not necessarily.\n\n```\nFIRST\n+----+-----------+------------+\n| ID | LPR | TIMESTAMP |\n+----+-----------+------------+\n| 1 | QWE123RTY | 05-05-2020 |\n+----+-----------+------------+\n| 2 | ZXC789IOP | 05-05-2020 |\n+----+-----------+------------+\n| 3 | ASD567FGH | 05-05-2020 |\n+----+-----------+------------+\n```\n\n```\nSECOND\n+----+-----------+------------+----------+\n| ID | LPR | TIMESTAMP | OWNER_ID |\n+----+-----------+------------+----------+\n| 1 | AAA111BBB | 04-05-2020 | 3 |\n+----+-----------+------------+----------+\n| 2 | QWE123RTY | 02-05-2020 | 1 |\n+----+-----------+------------+----------+\n| 3 | BBB222CCC | 14-05-2020 | 1 |\n+----+-----------+------------+----------+\n```\n\nI basically want to replicate `SELECT * FROM FIRST JOIN SECOND WHERE LPR=\"QWE123RTY\"` in prisma but to no avail. I cannot use a foreign key (at least to my knowledge) since the foreign key in SECOND might not always be present in FIRST as vice-versa.\n\nAn alternative that I think might work is to run two separate queries where I retrieve the matching records in SECOND and then run\n\n```\nprisma.FIRST.findMany({\n where: {\n LPR: { in: ['QWE123RTY', 'BBB222CCC'] }\n }\n})\n```\n\nHas anyone actually managed to do something like that?\n\n========================================\n\nCode:\n```text\nFIRST\n+----+-----------+------------+\n| ID | LPR       | TIMESTAMP  |\n+----+-----------+------------+\n| 1  | QWE123RTY | 05-05-2020 |\n+----+-----------+------------+\n| 2  | ZXC789IOP | 05-05-2020 |\n+----+-----------+------------+\n| 3  | ASD567FGH | 05-05-2020 |\n+----+-----------+------------+\n```\n\n```text\nSECOND\n+----+-----------+------------+----------+\n| ID | LPR       | TIMESTAMP  | OWNER_ID |\n+----+-----------+------------+----------+\n| 1  | AAA111BBB | 04-05-2020 | 3        |\n+----+-----------+------------+----------+\n| 2  | QWE123RTY | 02-05-2020 | 1        |\n+----+-----------+------------+----------+\n| 3  | BBB222CCC | 14-05-2020 | 1        |\n+----+-----------+------------+----------+\n```\n\n```text\nprisma.FIRST.findMany({\n    where: {\n        LPR: { in: ['QWE123RTY', 'BBB222CCC'] }\n    }\n})\n```\n\n```text\nSELECT * FROM FIRST JOIN SECOND WHERE LPR=\"QWE123RTY\"\n```\n\n```text\nawait prisma.$queryRaw`SELECT * FROM FIRST JOIN SECOND ON FIRST.LPR=SECOND.LPR`\n```\n\n```text\nprisma.$queryRaw\n```\n\n```text\nqueryRaw\n```\n\n========================================\n\nComments:\n- Did you read the manual specifically for full joins in mysql prisma.io/dataguide/mysql/reading-and-querying-data/&hellip; NB you don't need foreign keys to join tables..\n- I forgot to specify that I wanted to use the PrismaClient to do so.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Thank you for your comment, will update it promptly.","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":802}}315{"id":"stack-64434652","source":"stackoverflow","questionId":64434652,"title":"Convert Object to Object where A is contained in T","tags":["typescript","casting","type-conversion","prisma","prisma2"],"text":"Title: Convert Object to Object where A is contained in T\nTags: typescript, casting, type-conversion, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI'm working with Prisma to generate schemas and models for my database data.\n\nThere, I define a \"User\" model, which has this data (the type is automatically generated by Prisma):\n\n```\ntype User {\n name: string,\n nickName: string,\n sensitiveInfo1: string,\n sensitiveInfo2: string\n}\n```\n\nHowever, when my client requests this data, I can't send the sensitive info in the response payload.\n\nPrisma has a very handy way for defining a custom type:\n\n```\nimport { UserGetPayload } from \"./prisma/src/generated/client\"\n\n// now I define a custom type\nexport type UserPublicInfo = UserGetPayload\n\n// this gives me the type:\n// type UserPublicInfo {\n// name: ,\n// nickName: \n// }\n```\n\nNow, suppose I already have a user instance retrieved from the database, of type User. I wan't to cast it to \"UserPublicInfo\" in a way that the response payload only contains info of \"UserPublicInfo\".\n\nIf I cast an Object of type User like `user as UserPublicInfo` the type suggestions points to the right direction, showing only attributes of the subtype. However, the sensitive data still there.\n\nI'm junior at javascipt/typescript but I believe this has something to do with the Object's prototype. So how can I cast it this way?\n\n========================================\n\nCode:\n```text\ntype User {\n    name: string,\n    nickName: string,\n    sensitiveInfo1: string,\n    sensitiveInfo2: string\n}\n```\n\n```text\nimport { UserGetPayload } from \"./prisma/src/generated/client\"\n\n// now I define a custom type\nexport type UserPublicInfo = UserGetPayload<{\n    select: {\n        name: true,\n        nickName: true,\n    }\n}>\n\n// this gives me the type:\n// type UserPublicInfo {\n//        name: <whatever type name is in the schema>,\n//        nickName: <whatever type nickName is in the schema>\n// }\n```\n\n```text\nuser as UserPublicInfo\n```\n\n```text\ntype UserPublicInfo = Pick<User, 'name' | 'nickName'>\n```\n\n```text\ntype UserWithoutPrivate = Omit<User, 'sensitiveInfo1' | 'sensitiveInfo2'>\n```\n\n```text\ntype UserPublicInfo = {\n    name: string;\n    nickName: string;\n}\n```\n\n```text\nexport const userToPublic = (user: User): UserPublicInfo => {\n    const {sensitiveInfo1, sensitiveInfo2, ...rest} = user;\n    return user;\n}\n```\n\n```text\nname\n```\n\n```text\nnickName\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nsensitiveInfo1\n```\n\n```text\nsensitiveInfo2\n```\n\n```text\npick\n```\n\n```text\nomit\n```\n\n========================================\n\nComments:\n- Your answer is perfect! Thank you. Is there any way I could tell lodash or typescript itself to pick all the elements defined by the subtype? Like _.pick(User, UserPublicInfo). This would be much better than explicitly picking attributes defined by the subtype.\n- Btw, the last line of your example in the TS playground link was kind of broken, did you noticed too?","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":134,"estimatedTokens":734}}316{"id":"stack-71718442","source":"stackoverflow","questionId":71718442,"title":"Is it possible in prisma to filter by string length?","tags":["database","prisma"],"text":"Title: Is it possible in prisma to filter by string length?\nTags: database, prisma\nSource: Stack Overflow\n\nQuestion:\nIs it possible in prisma to filter by string length?\n\nFor example, I would like to receive records whose name is 10 characters long.\n\n========================================\n\nCode:\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Employee {\n  employeeId Int      @id @default(autoincrement())\n  first_name String\n  hire_date  DateTime\n}\n```\n\n```js\nimport { Prisma, PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient({\n  log: ['query', 'info', 'warn'],\n});\n\n// A `main` function so that you can use async/await\nasync function main() {\n\n  const result =\n    await prisma.$queryRaw`SELECT * FROM \"public\".\"Employee\" WHERE LENGTH(first_name) <= 5`;\n\n  console.log(result);\n}\nmain()\n  .catch((e) => {\n    throw e;\n  })\n  .finally(async () => {\n    await prisma.$disconnect();\n  });\n```\n\n```js\nprisma:info Starting a postgresql pool with 13 connections.\nprisma:query SELECT * FROM \"public\".\"Employee\" WHERE LENGTH(first_name) <= 5\n[\n  {\n    employeeId: 1,\n    first_name: 'John',\n    hire_date: '2022-03-10T00:00:00+00:00'\n  }\n]\n```\n\n```text\nfirst_name\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":322}}317{"id":"stack-55332526","source":"stackoverflow","questionId":55332526,"title":"How to resolve nested input types on graphql mutation","tags":["javascript","graphql","prisma"],"text":"Title: How to resolve nested input types on graphql mutation\nTags: javascript, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nSo I'm having issues trying to resolve a mutation that contains nested input types from another input type, correct me if I'm doing a wrong design with the models.\n\nThis is the mutation, I'm using Playground to check it out:\n\n```\nmutation{\n createOrganization(\n name: \"Bitas\"\n staff: [\n {\n firstName: \"Albert\"\n lastName: \"Chavez\"\n position: \"Developer\"\n contactInformation:[\n {\n email: \"hola@mail.com\"\n phone:\"9187631\"\n linkedin: \"whatever\"\n },\n {\n email: \"hola2@mail.com\"\n phone:\"91876312\"\n linkedin: \"whatever2\"\n }\n ]\n }\n ]\n ){\n name\n staff{\n firstName\n contactInformation{\n email\n }\n }\n }\n}\n```\n\nThis mutation is creating a relationship between Organization and Employee, which at the same time is creating a relationship between Employee and Contact Information... here are the schemas:\n\n```\ntype Organization {\n id: ID!\n name: String!\n staff: [Employee!]!\n}\n\ntype Employee {\n id: ID!\n firstName: String!\n lastName: String!\n position: String!\n contactInformation: [ContactInfo!]!\n belongsToOrg: Organization\n}\n\ninput employeeInput {\n firstName: String!\n lastName: String!\n position: String!\n contactInformation: [contactInfoInput!]!\n belongsToOrg: ID\n}\n\ntype ContactInfo {\n id: ID!\n email: String!\n phone: String!\n linkedin: String!\n belongsTo: Employee!\n}\n\ninput contactInfoInput {\n email: String!\n phone: String!\n linkedin: String!\n}\n```\n\nCorrect me if I'm not creating the mutations correctly\n\n```\ntype Mutation {\n createOrganization(name: String!, staff: [employeeInput!]): Organization!\n createEmployee(firstName: String!, lastName: String!, position:String!, contactInformation: [contactInfoInput!]!): Employee!\n}\n```\n\nAnd here are the functions to create: \n\n```\nfunction createEmployee(parent, args, context, info) {\n return context.prisma.createEmployee({\n firstName: args.firstName,\n lastName: args.lastName,\n position: args.position,\n contactInformation: {\n create: args.contactInformation\n },\n })\n}\n\nfunction createOrganization(parent, args, context, info) {\n return context.prisma.createOrganization({\n name: args.name,\n staff: {\n create: args.staff\n }\n })\n}\n\nfunction staff(parent, args, context) {\n return context.prisma.organization({id: parent.id}).staff();\n}\n\nfunction contactInformation(parent, args, context) {\n return context.prisma.employee({id: parent.id}).contactInformation()\n}\n\nfunction belongsTo(parent, args, context) {\n return context.prisma.contactInfo({id: parent.id}).belongsTo()\n}\n```\n\nSo when I hit the mutation on Playground, it gives me the error:\n\n**Reason: 'staff.create[0].contactInformation' Expected 'ContactInfoCreateManyWithoutEmployeeInput', found not an object.** \n\nCould please somebody explain me what this means?? Am I not designing correctly the schema or relationships?? Or perhaps is because too many levels of nested inputs??\nIf I console.log the contactInformation field on the createOrganization function the value is undefined.\n\nNote: *When creating a Employee, the nested mutation works fine.*\n\nThanks in advance.\n\n========================================\n\nCode:\n```text\nmutation{\n  createOrganization(\n    name: \"Bitas\"\n    staff: [\n      {\n        firstName: \"Albert\"\n        lastName: \"Chavez\"\n        position: \"Developer\"\n        contactInformation:[\n            {\n                email: \"hola@mail.com\"\n                phone:\"9187631\"\n                linkedin: \"whatever\"\n            },\n            {\n                email: \"hola2@mail.com\"\n                phone:\"91876312\"\n                linkedin: \"whatever2\"\n            }\n          ]\n        }\n    ]\n  ){\n    name\n    staff{\n      firstName\n      contactInformation{\n        email\n      }\n    }\n  }\n}\n```\n\n```text\ntype Organization {\n    id: ID!\n    name: String!\n    staff: [Employee!]!\n}\n\ntype Employee {\n    id: ID!\n    firstName: String!\n    lastName: String!\n    position: String!\n    contactInformation: [ContactInfo!]!\n    belongsToOrg: Organization\n}\n\ninput employeeInput {\n    firstName: String!\n    lastName: String!\n    position: String!\n    contactInformation: [contactInfoInput!]!\n    belongsToOrg: ID\n}\n\ntype ContactInfo {\n    id: ID!\n    email: String!\n    phone: String!\n    linkedin: String!\n    belongsTo: Employee!\n}\n\ninput contactInfoInput {\n    email: String!\n    phone: String!\n    linkedin: String!\n}\n```\n\n```text\ntype Mutation {\n    createOrganization(name: String!, staff: [employeeInput!]): Organization!\n    createEmployee(firstName: String!, lastName: String!, position:String!, contactInformation: [contactInfoInput!]!): Employee!\n}\n```\n\n```text\nfunction createEmployee(parent, args, context, info) {\n    return context.prisma.createEmployee({\n        firstName: args.firstName,\n        lastName: args.lastName,\n        position: args.position,\n        contactInformation: {\n            create: args.contactInformation\n        },\n    })\n}\n\nfunction createOrganization(parent, args, context, info) {\n    return context.prisma.createOrganization({\n        name: args.name,\n        staff: {\n            create: args.staff\n        }\n    })\n}\n\nfunction staff(parent, args, context) {\n    return context.prisma.organization({id: parent.id}).staff();\n}\n\nfunction contactInformation(parent, args, context) {\n    return context.prisma.employee({id: parent.id}).contactInformation()\n}\n\nfunction belongsTo(parent, args, context) {\n    return context.prisma.contactInfo({id: parent.id}).belongsTo()\n}\n```\n\n```text\ninput employeeInput {\n    firstName: String!\n    lastName: String!\n    position: String!\n    contactInformation: [contactInfoInput!]!\n    belongsToOrg: ID\n}\n```\n\n```text\ntype ContactInfo {\n    id: ID!\n    email: String!\n    phone: String!\n    linkedin: String!\n    belongsTo: Employee!\n}\n```\n\n```text\nfunction createOrganization(parent, args, context, info) {\n    return context.prisma.createOrganization({\n        name: args.name,\n        staff: {\n            create: args.staff\n        }\n    })\n}\n```\n\n```text\nfunction createOrganization(parent, args, context, info) {\n    const { staff } = args\n    return context.prisma.createOrganization({\n        name: args.name,\n        staff: {\n            create: staff.map((emp) => ({\n               firstName: emp.firstName,\n               lastName: emp.lastName,\n               position: emp.position,\n               contactInformation: {\n                   create: emp.contactInformation || []\n               }\n            }))\n        }\n    })\n}\n```\n\n```text\ncreateOrganization\n```\n\n```text\ncreateOrganization\n```\n\n```text\ncreateOrganization(name: String!, staff: [employeeInput!]): Organization!\n```\n\n```text\nstaff\n```\n\n```text\nemployeeInput\n```\n\n```text\nContactInformation\n```\n\n```text\ncontactInfoInput\n```\n\n```text\ncreate\n```\n\n```text\nconnect\n```\n\n```text\nupdate\n```\n\n```text\nupsert\n```\n\n```text\nargs.staff\n```\n\n```text\ncreate\n```\n\n```text\ncontactInformation\n```\n\n```text\nargs.staff\n```\n\n```text\nContactInfoCreateManyWithoutEmployeeInput\n```\n\n========================================\n\nComments:\n- Apparently this solution is not working... I got this error: Reason: 'staff.create[0].firstName' Expected non-null value, found null.\n- So I suppose I need to iterate the staff array that is passed... and then iterate over the contact information array.. is this correct?? If so, why the employee mutation doesn't need to iterate??\n- I updated code to iterate through `staff` array, I missed that earlier. In case of `createEmployee` mutation, you have only one relational field in `contactInfo` called `belongsTo` which is not being passed in input I guess and that is the reason mutation is working as you already have `create` for contactInfo. Things will break when `belongsTo` is set in input.","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":379,"estimatedTokens":1931}}318{"id":"stack-70833885","source":"stackoverflow","questionId":70833885,"title":"Instantiating PrismaClient with Next.js in production","tags":["prisma"],"text":"Title: Instantiating PrismaClient with Next.js in production\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nPrisma documentation recommends to instantiate Prisma Client as below to avoid infamous `Already 10 Prisma Clients are actively running` issue;\n\n```\nimport { PrismaClient } from '@prisma/client'\n\ndeclare global {\n // allow global `var` declarations\n // eslint-disable-next-line no-var\n var prisma: PrismaClient | undefined\n}\n\nexport const prisma =\n global.prisma ||\n new PrismaClient({\n log: ['query'],\n })\n\nif (process.env.NODE_ENV !== 'production') global.prisma = prisma\n```\n\nit runs OK in dev environment. What I need to ask, do I need this `process.env.NODE_ENV !== 'production'` check? Should I instantiate Prisma Client in production differently?\n\n========================================\n\nCode:\n```text\nimport { PrismaClient } from '@prisma/client'\n\ndeclare global {\n  // allow global `var` declarations\n  // eslint-disable-next-line no-var\n  var prisma: PrismaClient | undefined\n}\n\nexport const prisma =\n  global.prisma ||\n  new PrismaClient({\n    log: ['query'],\n  })\n\nif (process.env.NODE_ENV !== 'production') global.prisma = prisma\n```\n\n```text\nAlready 10 Prisma Clients are actively running\n```\n\n```text\nprocess.env.NODE_ENV !== 'production'\n```\n\n```text\nNODE_ENV\n```\n\n```text\nglobal\n```\n\n```text\nPrismaClient\n```\n\n========================================\n\nComments:\n- Useful for me: prisma.io/docs/guides/other/troubleshooting-orm/help-article&zwnj;&#8203;s/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":373}}319{"id":"stack-61407977","source":"stackoverflow","questionId":61407977,"title":"Prisma2 prisma introspect returning weird values for foreign keys","tags":["postgresql","prisma","prisma-graphql"],"text":"Title: Prisma2 prisma introspect returning weird values for foreign keys\nTags: postgresql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI have two tables, `User` and `Relationship`. The tables are used to store a parent child relationship. I am using `Postgres` \n\n// schema.sql\n\n```\nCREATE TABLE \"public\".\"Relationships\" (\n id SERIAL PRIMARY KEY NOT NULL,\n parent_id INT NOT NULL,\n FOREIGN KEY (parent_id) REFERENCES \"User\" (id),\n child_id INT NOT NULL,\n FOREIGN KEY (child_id) REFERENCES \"User\" (id)\n)\n\nCREATE TABLE \"public\".\"User\" (\n id SERIAL PRIMARY KEY NOT NULL,\n name VARCHAR(128) NOT NULL,\n email VARCHAR(128) UNIQUE,\n password VARCHAR(128) NOT NULL,\n isChild BOOLEAN NOT NULL DEFAULT false\n created_at TIMESTAMP NOT NULL DEFAULT NOW();\n);\n```\n\nWhen I run `npx prisma introspect` the following is returned in the `schema.prisma` file. \n\n// schema.prisma\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\nmodel Relationships {\n child_id Int\n id Int @default(autoincrement()) @id\n parent_id Int\n User_Relationships_child_idToUser User @relation(\"Relationships_child_idToUser\", fields: [child_id], references: [id])\n User_Relationships_parent_idToUser User @relation(\"Relationships_parent_idToUser\", fields: [parent_id], references: [id])\n}\n\nmodel User {\n created_at DateTime @default(now())\n email String? @unique\n id Int @default(autoincrement()) @id\n ischild Boolean @default(false)\n name String?\n password String\n Relationships_Relationships_child_idToUser Relationships[] @relation(\"Relationships_child_idToUser\")\n Relationships_Relationships_parent_idToUser Relationships[] @relation(\"Relationships_parent_idToUser\")\n}\n```\n\nI dont understand what `User_Relationships_child_idToUser` and `User_Relationships_parent_idToUser` are and why they are not just the simple syntax that appears for foreign keys in the Prisma docs tutorial.\n\n========================================\n\nCode:\n```text\nCREATE TABLE \"public\".\"Relationships\" (\n    id SERIAL PRIMARY KEY NOT NULL,\n    parent_id INT NOT NULL,\n    FOREIGN KEY (parent_id) REFERENCES \"User\" (id),\n    child_id INT NOT NULL,\n    FOREIGN KEY (child_id) REFERENCES \"User\" (id)\n)\n\nCREATE TABLE \"public\".\"User\" (\n    id SERIAL PRIMARY KEY NOT NULL,\n    name VARCHAR(128) NOT NULL,\n    email VARCHAR(128) UNIQUE,\n    password VARCHAR(128) NOT NULL,\n    isChild BOOLEAN NOT NULL DEFAULT false\n    created_at TIMESTAMP NOT NULL DEFAULT NOW();\n);\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\nmodel Relationships {\n  child_id                           Int\n  id                                 Int  @default(autoincrement()) @id\n  parent_id                          Int\n  User_Relationships_child_idToUser  User @relation(\"Relationships_child_idToUser\", fields: [child_id], references: [id])\n  User_Relationships_parent_idToUser User @relation(\"Relationships_parent_idToUser\", fields: [parent_id], references: [id])\n}\n\nmodel User {\n  created_at                                  DateTime        @default(now())\n  email                                       String?         @unique\n  id                                          Int             @default(autoincrement()) @id\n  ischild                                     Boolean         @default(false)\n  name                                        String?\n  password                                    String\n  Relationships_Relationships_child_idToUser  Relationships[] @relation(\"Relationships_child_idToUser\")\n  Relationships_Relationships_parent_idToUser Relationships[] @relation(\"Relationships_parent_idToUser\")\n}\n```\n\n```text\nUser\n```\n\n```text\nRelationship\n```\n\n```text\nPostgres\n```\n\n```text\nnpx prisma introspect\n```\n\n```text\nschema.prisma\n```\n\n```text\nUser_Relationships_child_idToUser\n```\n\n```text\nUser_Relationships_parent_idToUser\n```\n\n```text\nmodel Relationships {\n  child_id  Int\n  id        Int  @default(autoincrement()) @id\n  parent_id Int\n  child     User @relation(\"Relationships_child_idToUser\", fields: [child_id], references: [id])\n  parent    User @relation(\"Relationships_parent_idToUser\", fields: [parent_id], references: [id])\n}\n```\n\n```text\n@relation\n```\n\n```text\nUser_Relationships_parent_idToUser\n```\n\n```text\nUser_Relationships_child_idToUser\n```\n\n========================================\n\nComments:\n- Why does the example code show it much more simply?\n- Which example code are you referring to exactly? I guess one big difference here is that in your example you have *two* relations between `User` and `Relationship` (because you have two foreign keys defined) while most example code snippets only use a single foreign key.\n- I was referring to the prisma.io start from scratch tutorial. You suggestion makes a lot of sense though.","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":172,"estimatedTokens":1213}}320{"id":"stack-51497073","source":"stackoverflow","questionId":51497073,"title":"Am I supposed to re-type my fields over and over, or am I thinking though this wrong?","tags":["graphql","apollo","prisma"],"text":"Title: Am I supposed to re-type my fields over and over, or am I thinking though this wrong?\nTags: graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm sort of getting my head around Apollo/GraphQL/Prisma/Yoga, but the one bit I'm always getting stuck on is, there's just so much doubling-up going on. \n\nSay I have a schema type called `Client`, which has `title`, `firstName`, `lastName`, `email`, `phone`, `address` etc etc. \n\nWhen I make a mutation, I need to type out all the fields:\n\n```\nconst result = await this.props.saveClientMutation({\n variables: {\n title,\n firstName,\n lastName,\n email,\n (etc)\n }\n})\n```\n\nthis then goes to my actual graphQL definition in my client, where I type out all the fields again (twice!)\n\n```\nmutation SAVE_CLIENT_MUTATION ($title: String!, $firstName: String!, $lastName: String!, $email: String!) {\n login(title: $title, firstName: $firstName, lastName: $lastName, email: $email) {\n client {\n id\n firstName\n lastName\n }\n }\n}\n```\n\nthis then goes to the resolver in my server (which, thank god for spread operators), then to my database schema where I essentially type all the same fields a fourth time. \n\nThis just seems like a gargantuan surface area for bugs and inconsistencies. Have I thoroughly misunderstood how this is meant to work, or is there meant to be this crazy amount of re-typing?\n\n========================================\n\nCode:\n```text\nconst result = await this.props.saveClientMutation({\n  variables: {\n    title,\n    firstName,\n    lastName,\n    email,\n    (etc)\n  }\n})\n```\n\n```text\nmutation SAVE_CLIENT_MUTATION ($title: String!, $firstName: String!, $lastName: String!, $email: String!) {\n  login(title: $title, firstName: $firstName, lastName: $lastName, email: $email) {\n    client {\n      id\n      firstName\n      lastName\n    }\n  }\n}\n```\n\n```text\nClient\n```\n\n```text\ntitle\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\nemail\n```\n\n```text\nphone\n```\n\n```text\naddress\n```\n\n```text\n# Reusable type fields\ninterface IClient {\n    title: String\n    firstName: String\n    lastName: String\n    email: String\n    phone: String\n    address: String\n}\n\ntype Client implements IClient {\n    # You must re-type interface items\n    title: String\n    firstName: String\n    lastName: String\n    email: String\n    phone: String\n    address: String\n}\n\n# Reusable mutation input variables\ninput ClientInput {\n    title: String\n    firstName: String\n    lastName: String\n    email: String\n    phone: String\n    address: String\n}\n\n# Reusable query fields\nfragment ClientParts on Client {\n  firstName\n  lastName\n}\n\n# You can use your input type & fragment here\n# although the input does change the structure from your example\nmutation SAVE_CLIENT_MUTATION ($input: ClientInput!) {\n    login(input: $input) {\n      client {\n        ...ClientParts\n        id\n      }\n    }\n}\n```\n\n========================================\n\nComments:\n- Cheers Edward, that all makes sense.","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":149,"estimatedTokens":733}}321{"id":"stack-73265760","source":"stackoverflow","questionId":73265760,"title":"Prisma asking for required ID which is marked as default(autoincrement() in schema","tags":["python","python-3.x","prisma"],"text":"Title: Prisma asking for required ID which is marked as default(autoincrement() in schema\nTags: python, python-3.x, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using the Python Prisma client. Below is my `schema.prisma` which should make it so that whenever I create something in the `serververification` table, it will have an autoincremented ID on that inserted data.\n\nThe database is a MySQL database.\n\n```\nmodel serververification {\n id Int @id @default(autoincrement())\n guildId String @db.VarChar(20)\n enabled Boolean @db.Bit(1)\n panelMessageId String? @db.VarChar(20)\n panelChannelId String? @db.VarChar(20)\n logChannelId String? @db.VarChar(20)\n unverifiedRoleId String? @db.VarChar(20)\n verifiedRoleIds String? @db.LongText\n\n @@index([guildId], map: \"guildId_fkey\")\n}\n```\n\nHowever, this does not seem to be the case. If I don't personally specify an ID I get an error stating that A value is required but not set. I'm not entirely sure what I've gone wrong. The schema is up to date with the database, I have ran all necessary commands\n\n```\nyarn prisma generate\nyarn prisma db push\nyarn prisma migrate dev\nyarn prisma db pull\n```\n\nCode where I create the new data to insert into the database, notice how I do not include a `id` key value, because the schema specifies that it shouldn't require me to, since the field is an auto incremented integer ID.\n\n```\nawait self.client.prisma.serververification.create(\n data={\n \"guildId\": str(interaction.guild_id),\n \"enabled\": True,\n \"panelMessageId\": str(panel_message.id),\n \"panelChannelId\": str(panel_channel_id.id),\n \"logChannelId\": None,\n \"unverifiedRoleIds\": str(unverified_role_id.id),\n }\n )\n```\n\nPython prisma version: v0.6.6\nother version information:\n\n```\n{\n \"dependencies\": {\n \"@prisma/client\": \"^4.1.1\",\n \"prisma\": \"^4.1.1\"\n }\n}\n```\n\nerror:\n\n```\nprisma.errors.FieldNotFoundError: Failed to validate the query: `Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at `Mutation.createOneserververification.data.serververificationCreateInput.unverifiedRoleIds`: Field does not exist on enclosing type., Query parsing/validation error at `Mutation.createOneserververification.data.serververificationUncheckedCreateInput.unverifiedRoleIds`: Field does not exist on enclosing type.]` at `Mutation.createOneserververification.data`\n```\n\nhttps://i.sstatic.net/bItUq.png\n\n========================================\n\nCode:\n```text\nmodel serververification {\n  id               Int     @id @default(autoincrement())\n  guildId          String  @db.VarChar(20)\n  enabled          Boolean @db.Bit(1)\n  panelMessageId   String? @db.VarChar(20)\n  panelChannelId   String? @db.VarChar(20)\n  logChannelId     String? @db.VarChar(20)\n  unverifiedRoleId String? @db.VarChar(20)\n  verifiedRoleIds  String? @db.LongText\n\n  @@index([guildId], map: \"guildId_fkey\")\n}\n```\n\n```text\nyarn prisma generate\nyarn prisma db push\nyarn prisma migrate dev\nyarn prisma db pull\n```\n\n```py\nawait self.client.prisma.serververification.create(\n            data={\n                \"guildId\": str(interaction.guild_id),\n                \"enabled\": True,\n                \"panelMessageId\": str(panel_message.id),\n                \"panelChannelId\": str(panel_channel_id.id),\n                \"logChannelId\": None,\n                \"unverifiedRoleIds\": str(unverified_role_id.id),\n            }\n        )\n```\n\n```text\n{\n  \"dependencies\": {\n    \"@prisma/client\": \"^4.1.1\",\n    \"prisma\": \"^4.1.1\"\n  }\n}\n```\n\n```text\nprisma.errors.FieldNotFoundError: Failed to validate the query: `Unable to match input value to any allowed input type for the field. Parse errors: [Query parsing/validation error at `Mutation.createOneserververification.data.serververificationCreateInput.unverifiedRoleIds`: Field does not exist on enclosing type., Query parsing/validation error at `Mutation.createOneserververification.data.serververificationUncheckedCreateInput.unverifiedRoleIds`: Field does not exist on enclosing type.]` at `Mutation.createOneserververification.data`\n```\n\n```text\nschema.prisma\n```\n\n```text\nserververification\n```\n\n```text\nid\n```\n\n```text\nmodel serververification {\n  id               Int     @id @default(autoincrement())\n  guildId          String  @client.VarChar(20)\n  enabled          Boolean @client.Bit(1)\n  panelMessageId   String? @client.VarChar(20)\n  panelChannelId   String? @client.VarChar(20)\n  logChannelId     String? @client.VarChar(20)\n  unverifiedRoleId String? @client.VarChar(20)\n  verifiedRoleIds  String? @client.LongText\n\n  @@index([guildId], map: \"guildId_fkey\")\n}\n```\n\n```text\nserververification = await db.serververification.create(\n        data = {\n                \"guildId\":\"abcdefgh\",\n                \"enabled\": True,\n                \"panelMessageId\": \"12345678\",\n                \"panelChannelId\": \"qwerty\",\n                \"logChannelId\": None,\n                \"unverifiedRoleId\": \"poiuyt\",\n        }\n    )\n\n    print(f'created serververification: {serververification.json(indent=2, sort_keys=True)}')\n\n    found = await db.serververification.find_unique(where={'id': serververification.id})\n    assert found is not None\n    print(f'found serververification: {found.json(indent=2, sort_keys=True)}')\n```\n\n```text\ncreated serververification: {\n  \"enabled\": true,\n  \"guildId\": \"abcdefgh\",\n  \"id\": 4,\n  \"logChannelId\": null,\n  \"panelChannelId\": \"qwerty\",\n  \"panelMessageId\": \"12345678\",\n  \"unverifiedRoleId\": \"poiuyt\",\n  \"verifiedRoleIds\": null\n}\nfound serververification: {\n  \"enabled\": true,\n  \"guildId\": \"abcdefgh\",\n  \"id\": 4,\n  \"logChannelId\": null,\n  \"panelChannelId\": \"qwerty\",\n  \"panelMessageId\": \"12345678\",\n  \"unverifiedRoleId\": \"poiuyt\",\n  \"verifiedRoleIds\": null\n}\n```\n\n```text\nunverifiedRoleId\n```\n\n```text\ns\n```\n\n```text\nunverifiedRoleId\n```\n\n```text\nunverifiedRoleIds\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":203,"estimatedTokens":1448}}322{"id":"stack-76250065","source":"stackoverflow","questionId":76250065,"title":"Request error PrismaClientValidationError on NextJS 13","tags":["javascript","typescript","next.js","prisma","planetscale"],"text":"Title: Request error PrismaClientValidationError on NextJS 13\nTags: javascript, typescript, next.js, prisma, planetscale\nSource: Stack Overflow\n\nQuestion:\nI'm making a school project and I'm using NextJS 13, and trying to connect to the MYSQL database using Prisma with PlanetScale, but while trying to register a user I'm getting:\n\n```\nRequest error PrismaClientValidationError:\nInvalid `prisma.user.create()` invocation:\n\n{\n data: {\n+ cpf: String,\n+ name: String,\n+ email: String,\n+ password: String,\n+ phone: String,\n+ gender: String,\n+ birth: DateTime,\n+ city: String,\n+ state: String,\n+ school: String,\n+ bio: String,\n? avatar?: String | null\n }\n}\n\nArgument cpf for data.cpf is missing.\nArgument name for data.name is missing.\nArgument email for data.email is missing.\nArgument password for data.password is missing.\nArgument phone for data.phone is missing.\nArgument gender for data.gender is missing.\nArgument birth for data.birth is missing.\nArgument city for data.city is missing.\nArgument state for data.state is missing.\nArgument school for data.school is missing.\nArgument bio for data.bio is missing.\n```\n\nThe Code on src/app/api/user :\n\n```\nimport prisma from \"../../../lib/prisma\";\nimport { NextResponse } from \"next/server\"\n\nexport async function POST(request) {\n const body = request.body\n try {\n const newUser = await prisma.user.create({\n data: {\n cpf: body.cpf,\n name: body.name,\n email: body.email,\n password: body.password,\n phone: body.phone,\n gender: body.gender,\n birth: body.birth,\n city: body.city,\n state: body.state,\n school: body.school,\n bio: body.bio,\n // avatar: body.avatar || null,\n }\n })\n return NextResponse.json({ data: newUser, success: true });\n } catch (error) {\n console.error('Request error', error)\n return NextResponse.json({ error: 'Error creating user', success: false }, { status: 500 });\n }\n \n}\n```\n\nThe schema.prisma:\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n relationMode = \"prisma\"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n cpf String @unique\n name String\n email String @unique\n password String\n phone String\n gender String\n birth DateTime @db.Date\n city String\n state String\n school String\n bio String\n avatar String?\n}\n```\n\nAnd the code on src/app/login/page.tsx:\n\n```\nasync function handleSubmit(e: React.FormEvent) {\n e.preventDefault();\n let body = { cpf, name, email, password, phone, gender, birth, city, state, school, bio};\n try {\n const response = await fetch('/api/user', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (response.status !== 200) {\n throw new Error(await response.text())\n } else {\n console.log('Cadastro realizado com sucesso!');\n }\n } catch (error) {\n console.log(body);\n console.log(error);\n\n }\n }\n```\n\nIf i modify the API code to :\n\n```\nconst newUser = await prisma.user.create({\n data: {\n cpf: \"12345678901\",\n name: \"John Doe\",\n email: \"johndoe@example.com\",\n password: \"password123\",\n phone: \"1234567890\",\n gender: \"male\",\n birth: new Date(),\n city: \"New York\",\n state: \"NY\",\n school: \"Johns Hopkins University\",\n bio: \"I am a software engineer and I love to code.\",\n }\n});\n```\n\nIt will work, already tried to change and format birthdate field, because i thought it was the issue, but same error\n\n========================================\n\nCode:\n```text\nRequest error PrismaClientValidationError:\nInvalid `prisma.user.create()` invocation:\n\n{\n  data: {\n+   cpf: String,\n+   name: String,\n+   email: String,\n+   password: String,\n+   phone: String,\n+   gender: String,\n+   birth: DateTime,\n+   city: String,\n+   state: String,\n+   school: String,\n+   bio: String,\n?   avatar?: String | null\n  }\n}\n\nArgument cpf for data.cpf is missing.\nArgument name for data.name is missing.\nArgument email for data.email is missing.\nArgument password for data.password is missing.\nArgument phone for data.phone is missing.\nArgument gender for data.gender is missing.\nArgument birth for data.birth is missing.\nArgument city for data.city is missing.\nArgument state for data.state is missing.\nArgument school for data.school is missing.\nArgument bio for data.bio is missing.\n```\n\n```js\nimport prisma from \"../../../lib/prisma\";\nimport { NextResponse } from \"next/server\"\n\nexport async function POST(request) {\n    const body = request.body\n    try {\n        const newUser = await prisma.user.create({\n            data: {\n                cpf: body.cpf,\n                name: body.name,\n                email: body.email,\n                password: body.password,\n                phone: body.phone,\n                gender: body.gender,\n                birth: body.birth,\n                city: body.city,\n                state: body.state,\n                school: body.school,\n                bio: body.bio,\n                // avatar: body.avatar || null,\n            }\n        })\n        return NextResponse.json({ data: newUser, success: true });\n    } catch (error) {\n        console.error('Request error', error)\n        return NextResponse.json({ error: 'Error creating user', success: false }, { status: 500 });\n    }\n    \n}\n```\n\n```text\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n  relationMode = \"prisma\"\n}\n\nmodel User {\n  id           Int         @id @default(autoincrement())\n  cpf          String      @unique\n  name         String\n  email        String      @unique\n  password     String\n  phone        String\n  gender       String\n  birth        DateTime    @db.Date\n  city         String\n  state        String\n  school       String\n  bio          String\n  avatar       String?\n}\n```\n\n```text\nasync function handleSubmit(e: React.FormEvent<HTMLFormElement>) {\n    e.preventDefault();\n    let body = { cpf, name, email, password, phone, gender, birth, city, state, school, bio};\n    try {\n      const response = await fetch('/api/user', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify(body),\n      })\n      if (response.status !== 200) {\n        throw new Error(await response.text())\n      } else {\n        console.log('Cadastro realizado com sucesso!');\n      }\n    } catch (error) {\n      console.log(body);\n      console.log(error);\n\n    }\n  }\n```\n\n```js\nconst newUser = await prisma.user.create({\n  data: {\n    cpf: \"12345678901\",\n    name: \"John Doe\",\n    email: \"johndoe@example.com\",\n    password: \"password123\",\n    phone: \"1234567890\",\n    gender: \"male\",\n    birth: new Date(),\n    city: \"New York\",\n    state: \"NY\",\n    school: \"Johns Hopkins University\",\n    bio: \"I am a software engineer and I love to code.\",\n  }\n});\n```\n\n```text\nconst body = request.body\n```\n\n```text\nexport async function POST(request) {\n    const body = await request.json()\n```\n\n```text\nroute\n```\n\n```text\nPOST\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":306,"estimatedTokens":1718}}323{"id":"stack-71960048","source":"stackoverflow","questionId":71960048,"title":"Get unique nested value with Prisma","tags":["javascript","database","prisma"],"text":"Title: Get unique nested value with Prisma\nTags: javascript, database, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a relationship that looks like this:\n\n```\nmodel Fighter {\n id Int @id @default(autoincrement())\n name String\n image String?\n description String?\n\n battles Battle[]\n votes Vote[]\n}\n\nmodel Vote {\n Fighter Fighter @relation(fields: [fighterId], references: [id])\n fighterId Int\n Battle Battle @relation(fields: [battleId], references: [id])\n battleId Int\n count Int @default(0)\n\n @@id([fighterId, battleId])\n}\n\nmodel Battle {\n id Int @id @default(autoincrement())\n slug String @unique\n name String\n fighters Fighter[]\n votes Vote[]\n}\n```\n\nA battle has multiple fighters and there is a Vote model which count the vote for each fighter in a battle. I want to retrieve a battle, include the fighters and include the vote for each fighter. I made this query:\n\n```\nprisma.battle.findMany({\n take: count,\n skip: skip,\n include: {\n fighters: {\n include: {\n votes: {\n select: {\n count: true\n }\n }\n }\n }\n }\n});\n```\n\nWhich solves approximately my issue because in the result a fighter has an array of votes, like this:\n\n```\n{\n \"id\": 2,\n \"slug\": \"Random-1\",\n \"name\": \"Random 1\",\n \"fighters\": [\n {\n \"id\": 3,\n \"name\": \"1 dragon\",\n \"image\": null,\n \"votes\": [\n {\n \"count\": 3\n }\n ]\n },\n {\n \"id\": 6,\n \"name\": \"1 hero\",\n \"image\": null,\n \"votes\": [\n {\n \"count\": 1\n }\n ]\n }\n ]\n}\n```\n\nBut what I would like is, for the best but I doubt it's possible:\n\n```\n{\n \"id\": 6,\n \"name\": \"1 hero\",\n \"image\": null,\n \"votes\": 1\n}\n```\n\nTo have the count of votes directly in my fighter object or at least, only one vote in the fighter object\n\n```\n{\n \"id\": 6,\n \"name\": \"1 hero\",\n \"image\": null,\n \"votes\": {\n \"count\": 1\n }\n}\n```\n\nI don't know if my issue is a schema problem between my models or if I can solve it with the Prisma queries. I tried to use the `include` and `select` API from Prisma but I couldn't solve this. Does anyone have an idea about this?\n\n========================================\n\nCode:\n```text\nmodel Fighter {\n  id          Int     @id @default(autoincrement())\n  name        String\n  image       String?\n  description String?\n\n  battles Battle[]\n  votes   Vote[]\n}\n\nmodel Vote {\n  Fighter   Fighter @relation(fields: [fighterId], references: [id])\n  fighterId Int\n  Battle    Battle  @relation(fields: [battleId], references: [id])\n  battleId  Int\n  count     Int     @default(0)\n\n  @@id([fighterId, battleId])\n}\n\nmodel Battle {\n  id       Int       @id @default(autoincrement())\n  slug     String    @unique\n  name     String\n  fighters Fighter[]\n  votes    Vote[]\n}\n```\n\n```js\nprisma.battle.findMany({\n  take: count,\n  skip: skip,\n  include: {\n    fighters: {\n      include: {\n        votes: {\n          select: {\n            count: true\n          }\n        }\n      }\n    }\n  }\n});\n```\n\n```json\n{\n    \"id\": 2,\n    \"slug\": \"Random-1\",\n    \"name\": \"Random 1\",\n    \"fighters\": [\n        {\n            \"id\": 3,\n            \"name\": \"1 dragon\",\n            \"image\": null,\n            \"votes\": [\n                {\n                    \"count\": 3\n                }\n            ]\n        },\n        {\n            \"id\": 6,\n            \"name\": \"1 hero\",\n            \"image\": null,\n            \"votes\": [\n                {\n                    \"count\": 1\n                }\n            ]\n        }\n    ]\n}\n```\n\n```json\n{\n  \"id\": 6,\n  \"name\": \"1 hero\",\n  \"image\": null,\n  \"votes\":  1\n}\n```\n\n```json\n{\n  \"id\": 6,\n  \"name\": \"1 hero\",\n  \"image\": null,\n  \"votes\": {\n     \"count\": 1\n  }\n}\n```\n\n```text\ninclude\n```\n\n```text\nselect\n```\n\n```js\nimport { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n  await prisma.battle.create({\n    data: {\n      name: 'Battle of the Vowels',\n      slug: 'battle-of-the-vowels',\n      fighters: {\n        create: {\n          name: 'Kabal',\n          description:\n            'Kabal is a fictional character in the Star Wars franchise. He is a member of the Jedi Order.',\n          image:\n            'https://vignette.wikia.nocookie.net/starwars/images/7/7e/Kabal_HS-SWE.png/revision/latest?cb=20170504075154',\n          votes: {\n            create: {\n              battleId: 1,\n            },\n          },\n        },\n      },\n    },\n  });\n\n  //\n  // Updated Query\n  //\n  const battle = await prisma.battle.findMany({\n    // take: count,\n    // skip: skip,\n    include: {\n      fighters: {\n        include: {\n          _count: {\n            select: {\n              votes: true,\n            },\n          },\n        },\n      },\n    },\n  });\n\n  console.log(JSON.stringify(battle, null, 2));\n}\n\nmain()\n  .catch((e) => {\n    throw e;\n  })\n  .finally(async () => {\n    await prisma.$disconnect();\n  });\n```\n\n```json\n[\n  {\n    \"id\": 1,\n    \"slug\": \"battle-of-the-vowels\",\n    \"name\": \"Battle of the Vowels\",\n    \"fighters\": [\n      {\n        \"id\": 1,\n        \"name\": \"Kabal\",\n        \"image\": \"https://vignette.wikia.nocookie.net/starwars/images/7/7e/Kabal_HS-SWE.png/revision/latest?cb=20170504075154\",\n        \"description\": \"Kabal is a fictional character in the Star Wars franchise. He is a member of the Jedi Order.\",\n        \"_count\": {\n          \"votes\": 1\n        }\n      }\n    ]\n  }\n]\n```\n\n========================================\n\nComments:\n- Thanks it works! I didn't figured out where I had to put the `_count` clause when I tried it. For the one who comes to this answer I had to change my `Vote` relation, remove the `@@id([fighterId, battleId])` and `count` and add an `id` to it\n- Is it possible to create a `votes` inside the creation of `battle` without giving the `battleId` ? Since we are currently creating the battle, we don't know the current battle id","metadata":{"transformedAt":"2026-08-18T18:33:14.851Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":308,"estimatedTokens":1410}}324{"id":"stack-70513543","source":"stackoverflow","questionId":70513543,"title":"Is there a way to programmatically override a datasource url with nest config?","tags":["javascript","node.js","typescript","nestjs","prisma"],"text":"Title: Is there a way to programmatically override a datasource url with nest config?\nTags: javascript, node.js, typescript, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI've got a `app.config.ts` file with plenty of config variables that look like this:\n\n```\nexport const exampleConfig = (config: ConfigService) => {\n // Do stuff\n\n return config.get('EXAMPLE')\n}\n```\n\nAnd I've got my `schema.prisma` file which requires a database URL... Currently, I use this config file on my `app.module.ts` and on my `main.ts`:\n\n**AppModule:**\n\n```\nExampleModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: exampleConfig\n }),\n```\n\n**Main:**\n\n```\n[...]\nimport { ConfigService } from '@nestjs/config';\nimport { exampleConfig } from './config/app.config';\n[...]\n\n(async function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const configService = app.get(ConfigService);\n\n [...]\n\n app.exampleCallThatNeedsConfig(exampleConfig(configService));\n\n await app.listen(3000);\n})();\n```\n\nNotice how I always use @nestjs/config configService on my `app.config.ts`? The thing here is, my `schema.prisma` file needs a DB_URL, but I cannot use configService nor anything quite like that in there... I could use a env('DB_URL') as the docs tells me to do, but I'd like to keep using the same pattern all over my application, so I'd rather stick with configService\n\n========================================\n\nTop Answer:\nYou can also try the syntax below. By setting the DB URL in the database service, you don't need to do the `const prisma = new PrismaClient`in every other service.\n\n```\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\nimport { ConfigService } from '@nestjs/config';\n\n@Injectable()\nexport class DatabaseService extends PrismaClient implements OnModuleInit {\n constructor(private readonly configService: ConfigService) {\n super({\n datasources: {\n db: {\n url: configService.get('DATABASE_URL'),\n },\n },\n });\n }\n async onModuleInit() {\n await this.$connect();\n }\n}\n```\n\n========================================\n\nCode:\n```js\nexport const exampleConfig = (config: ConfigService) => {\n    // Do stuff\n\n    return config.get('EXAMPLE')\n}\n```\n\n```js\nExampleModule.forRootAsync({\n         imports: [ConfigModule],\n         inject: [ConfigService],\n         useFactory: exampleConfig\n    }),\n```\n\n```js\n[...]\nimport { ConfigService } from '@nestjs/config';\nimport { exampleConfig } from './config/app.config';\n[...]\n\n\n(async function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const configService = app.get(ConfigService);\n\n  [...]\n\n  app.exampleCallThatNeedsConfig(exampleConfig(configService));\n\n  await app.listen(3000);\n})();\n```\n\n```text\napp.config.ts\n```\n\n```text\nschema.prisma\n```\n\n```text\napp.module.ts\n```\n\n```text\nmain.ts\n```\n\n```text\napp.config.ts\n```\n\n```text\nschema.prisma\n```\n\n```js\n[...]\nimport { PrismaClient } from '@prisma/client'\nimport { exampleConfig } from './config/app.config';\n\n@Injectable()\nexport class PrismaService extends PrismaClient\n  implements OnModuleInit {\n\n[...]\n\nconst prisma = new PrismaClient({\n  datasources: {\n    db: {\n      url: exampleConfig(configService),\n    },\n  },\n})\n```\n\n```js\nimport { Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\nimport { ConfigService } from '@nestjs/config';\n\n@Injectable()\nexport class DatabaseService extends PrismaClient implements OnModuleInit {\n  constructor(private readonly configService: ConfigService) {\n    super({\n      datasources: {\n        db: {\n          url: configService.get('DATABASE_URL'),\n        },\n      },\n    });\n  }\n  async onModuleInit() {\n    await this.$connect();\n  }\n}\n```\n\n```text\nconst prisma = new PrismaClient\n```\n\n========================================\n\nComments:\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review\n- @camille you're totally right! I just edited my answer in order to improve it, thanks for the heads up!","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":189,"estimatedTokens":1043}}325{"id":"stack-73335287","source":"stackoverflow","questionId":73335287,"title":"How to access prisma studio when the app is already deployed on heroku","tags":["heroku","next.js","prisma","heroku-postgres"],"text":"Title: How to access prisma studio when the app is already deployed on heroku\nTags: heroku, next.js, prisma, heroku-postgres\nSource: Stack Overflow\n\nQuestion:\nI have a `next.js` app which im developing locally right now on development environment. Im calling on `npm run dev` my server and im running prisma studio with `\"dev\": \"next dev -p 3006 & npx prisma studio -p 3007\",`\n\nIm wondering how I can access prisma studio if my `next.js` app is already deployed on `heroku` for example. Prisma provides a guide about deploying to `heroku`, but there it is not mentioned how to access the database via prisma studio after deployment.\nhttps://www.prisma.io/docs/guides/deployment/deployment-guides/deploying-to-heroku\n\nDoes anybody have some experience here?\n\n========================================\n\nCode:\n```text\nnext.js\n```\n\n```text\nnpm run dev\n```\n\n```text\n\"dev\": \"next dev -p 3006 & npx prisma studio -p 3007\",\n```\n\n```text\nnext.js\n```\n\n```text\nheroku\n```\n\n```text\nheroku\n```\n\n========================================\n\nComments:\n- Can't you access it in the same way with your project's URL and the port?\n- this would mean everyone could see the live database having the url and port. actually, that would be really bad\n- Pretty sure there is a way of authentication or alike. People are not totally unaware of security concerns.\n- can you please provide more info on how this can be done? Why is the new project in the dashboard asking me to connect to a repo?\n- For anyone coming to this in 2024, the Data Browser production has been sunset. Looks like Prisma is recommending Data Studio for this now.","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":47,"estimatedTokens":402}}326{"id":"stack-72596799","source":"stackoverflow","questionId":72596799,"title":"Prisma with GraphQL - how to provide an explicit type for a specified array of strings - unique naming issue","tags":["typescript","graphql","prisma"],"text":"Title: Prisma with GraphQL - how to provide an explicit type for a specified array of strings - unique naming issue\nTags: typescript, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI am trying to figure out how to specify an explicit type for a field, that is defined in a prisma schema as having an enum value.\n\nIn my schema I have:\n\n```\nenum Category {\n CHANGE\n OPTION \n OTHER\n}\n```\n\nand a model that uses Category as follows:\n\n```\nmodel Issue {\n id String @id @default(dbgenerated(\"gen_random_uuid()\")) @db.Uuid\n title String\n description String\n category Category\n Template Template[]\n createdAt DateTime @default(now()) @db.Timestamptz(6) \n updatedAt DateTime @default(now()) @updatedAt @db.Timestamptz(6)\n User User[]\n}\n```\n\nThen in the back end, I have a model:\n\n```\nimport * as Prisma from \"@prisma/client\"\n\nimport { Field, ObjectType } from 'type-graphql'\nimport { BaseModel } from \"../shared/base.model\"\n// - I tried this but it didn't help: import { Category } from \"@generated\"\n\n@ObjectType()\nexport class Issue extends BaseModel implements Prisma.Issue {\n\n @Field() \n title: string\n\n @Field()\n description: string\n\n @Field(() => Category)\n category: Prisma.Category\n \n \n}\n```\n\nand an input file that both define 'category', I think I'm providing the right type, by referencing the Prisma enum (not sure if instead I'm supposed to reference the generated types).\n\n```\nimport { IsNotEmpty } from \"class-validator\"\nimport { Field, InputType } from \"type-graphql\"\nimport { Issue } from '../issue.model'\nimport * as Prisma from \"@prisma/client\"\n\n@InputType()\nexport class IssueInput implements Partial {\n @Field()\n @IsNotEmpty()\n title: string\n\n @Field()\n @IsNotEmpty()\n description: string\n\n @Field()\n @IsNotEmpty()\n category: Prisma.Category\n\n @Field()\n @IsNotEmpty()\n userId: string\n\n}\n```\n\nWhen I try to run yarn dev with this, I get an error that says:\n\nNoExplicitTypeError: Unable to infer GraphQL type from TypeScript\nreflection system. You need to provide explicit type for 'category' of\n'IssueInput' class\n\nHow can I figure out how to give a type to category in the IssueInput class? I can't find an example of how to do this.\n\nI tried adding: registerEnumType to both the IssueInput definition, and the Issue Model, using the idea set out below:\n\n```\nimport { IsNotEmpty } from \"class-validator\"\nimport { Field, InputType, registerEnumType } from \"type-graphql\"\nimport { Issue } from '../issue.model'\nimport * as Prisma from \"@prisma/client\"\n\nregisterEnumType(Prisma.Category, {\n name: \"Category\", // this one is mandatory\n description: \"Issue Category\", // this one is optional\n});\n\n@InputType()\nexport class IssueInput implements Partial {\n @Field()\n @IsNotEmpty()\n title: string\n\n @Field()\n @IsNotEmpty()\n description: string\n\n @Field()\n @IsNotEmpty()\n category: Prisma.Category\n\n @Field()\n @IsNotEmpty()\n userId: string\n\n}\n```\n\nI still get an error saying:\n\nNoExplicitTypeError: Unable to infer GraphQL type from TypeScript\nreflection system. You need to provide explicit type for 'category' of\n'IssueInput' class.\nat Object.findType\n\nWhen I try it like below, I get a console error that says Error: Schema must contain uniquely named types but contains multiple types named \"Category\". I only have one Category in the schema file.\n\nWithin my terminal, the error is expressed differently, it says:\n\nProperty 'category' in type 'IssueInput' is not assignable to the same\nproperty in base type 'Partial'. Type 'Category' is not\nassignable to type 'Category | undefined'.\nType '\"CHANGE\"' is not assignable to type 'Category | undefined'.\n\n```\nimport { IsNotEmpty } from \"class-validator\"\nimport { Field, InputType, registerEnumType } from \"type-graphql\"\nimport { Issue } from '../issue.model'\nimport * as Prisma from \"@prisma/client\"\n\nregisterEnumType(Prisma.Category, {\n name: \"Category\", // this one is mandatory\n description: \"Issue Category\", // this one is optional\n});\n\n@InputType()\nexport class IssueInput implements Partial {\n @Field()\n @IsNotEmpty()\n title: string\n\n @Field()\n @IsNotEmpty()\n description: string\n\n @Field(type => Prisma.Category)\n @IsNotEmpty()\n category: Prisma.Category\n // category: Prisma.Category | undefined -- this also does not solve the problem \n\n @Field()\n @IsNotEmpty()\n userId: string\n\n}\n```\n\n========================================\n\nCode:\n```text\nenum Category {\n  CHANGE\n  OPTION \n  OTHER\n}\n```\n\n```text\nmodel Issue {\n  id          String           @id @default(dbgenerated(\"gen_random_uuid()\")) @db.Uuid\n  title       String\n  description String\n  category    Category\n  Template    Template[]\n  createdAt   DateTime    @default(now()) @db.Timestamptz(6) \n  updatedAt   DateTime    @default(now()) @updatedAt @db.Timestamptz(6)\n  User        User[]\n}\n```\n\n```text\nimport * as Prisma from \"@prisma/client\"\n\nimport { Field, ObjectType } from 'type-graphql'\nimport { BaseModel } from \"../shared/base.model\"\n// - I tried this but it didn't help: import { Category } from \"@generated\"\n\n\n\n@ObjectType()\nexport class Issue extends BaseModel implements Prisma.Issue {\n\n    @Field()  \n    title: string\n\n    @Field()\n    description: string\n\n    @Field(() => Category)\n    category: Prisma.Category\n    \n    \n}\n```\n\n```text\nimport { IsNotEmpty } from \"class-validator\"\nimport { Field, InputType } from \"type-graphql\"\nimport { Issue } from '../issue.model'\nimport * as Prisma from \"@prisma/client\"\n\n\n@InputType()\nexport class IssueInput implements Partial<Issue> {\n    @Field()\n    @IsNotEmpty()\n    title: string\n\n    @Field()\n    @IsNotEmpty()\n    description: string\n\n    @Field()\n    @IsNotEmpty()\n    category: Prisma.Category\n\n    @Field()\n    @IsNotEmpty()\n    userId: string\n\n\n\n}\n```\n\n```text\nimport { IsNotEmpty } from \"class-validator\"\nimport { Field, InputType, registerEnumType } from \"type-graphql\"\nimport { Issue } from '../issue.model'\nimport * as Prisma from \"@prisma/client\"\n\n\nregisterEnumType(Prisma.Category, {\n  name: \"Category\", // this one is mandatory\n  description: \"Issue Category\", // this one is optional\n});\n\n\n@InputType()\nexport class IssueInput implements Partial<Issue> {\n    @Field()\n    @IsNotEmpty()\n    title: string\n\n    @Field()\n    @IsNotEmpty()\n    description: string\n\n    @Field()\n    @IsNotEmpty()\n    category: Prisma.Category\n\n    @Field()\n    @IsNotEmpty()\n    userId: string\n\n\n\n}\n```\n\n```text\nimport { IsNotEmpty } from \"class-validator\"\nimport { Field, InputType, registerEnumType } from \"type-graphql\"\nimport { Issue } from '../issue.model'\nimport * as Prisma from \"@prisma/client\"\n\n\nregisterEnumType(Prisma.Category, {\n  name: \"Category\", // this one is mandatory\n  description: \"Issue Category\", // this one is optional\n});\n\n\n@InputType()\nexport class IssueInput implements Partial<Issue> {\n    @Field()\n    @IsNotEmpty()\n    title: string\n\n    @Field()\n    @IsNotEmpty()\n    description: string\n\n    @Field(type => Prisma.Category)\n    @IsNotEmpty()\n    category: Prisma.Category\n    // category: Prisma.Category | undefined -- this also does not solve the problem  \n\n\n    @Field()\n    @IsNotEmpty()\n    userId: string\n\n\n\n}\n```\n\n```text\nimport { registerEnumType } from \"type-graphql\";\n\nregisterEnumType(Prisma.Category, {\n  name: \"Category\", // this one is mandatory\n  description: \"Issue Category\", // this one is optional\n});\n```\n\n========================================\n\nComments:\n- I tried to use this suggestion. Thank you for sharing it, but I still get rejected when I try this. I have updated by post to show the attempts - if you can see how I've got it wrong, I'd be grateful for the steer. Thank you\n- Try importing ‘reflect-metadata’ as early as possible and make sure ‘experimentalDecorators’ and ‘emitDecoratorMetadata’ is enabled (tsconfig).","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":344,"estimatedTokens":1916}}327{"id":"stack-72524735","source":"stackoverflow","questionId":72524735,"title":"Why isn't my schema connecting Product and Category?","tags":["graphql","apollo","prisma","prisma-graphql"],"text":"Title: Why isn't my schema connecting Product and Category?\nTags: graphql, apollo, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\n**Tryign to do**\nI am trying to Query my Products and to also show what Categories they are under.\n\nHere is my Prisma Schema\n\n```\nmodel Product {\n id String @id @default(uuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n name String @db.VarChar(80)\n description String @db.VarChar(240)\n ingredients String[]\n price Float\n category Category[] \n \n}\n\nmodel Category {\n id String @id @default(uuid())\n createdAt DateTime @default(now())\n name String \n product Product[]\n \n}\n```\n\nThis shows that there is a relationship between the Products and Categories\n\nHowever, when I query in Apollo Studio, it doesn't show up.\n\nhttps://i.sstatic.net/ONJNv.png\n\nHere is my schema in my Prisma Studio as well to show the relationship\n\nhttps://i.sstatic.net/LUbeG.png\n\nAny information would be greatly appreciated!\n\nHere is also the resolver.\n\n```\nexport const resolvers = {\n Query: { \n allCategories:(_parent:any, _args:any, context: Context) => {\n return context.prisma.category.findMany()\n },\n allProducts:(_parent:any, _args:any, context:Context) => {\n return context.prisma.product.findMany()\n },\n productById:(_parent: any, {id}, context: Context) => {\n return context.prisma.product.findUnique({\n where: {\n id\n }\n })\n },\n categoryById:(_parent:any, {id}, context: Context) => {\n return context.prisma.category.findUnique({\n where: {\n id\n }\n })\n },\n productsByCategory:(_parent:any, {category}, context: Context) => {\n return context.prisma.product.findMany({\n select: {\n category: true\n }\n })\n }\n },\n```\n\n========================================\n\nCode:\n```text\nmodel Product {\n  id String @id @default(uuid())\n  createdAt DateTime @default(now())\n  updatedAt DateTime @updatedAt\n  name String @db.VarChar(80)\n  description String @db.VarChar(240)\n  ingredients String[]\n  price Float\n  category Category[] \n  \n}\n\nmodel Category {\n    id String @id @default(uuid())\n    createdAt DateTime @default(now())\n    name String \n    product Product[]\n   \n}\n```\n\n```text\nexport const resolvers = {\n    Query: { \n        allCategories:(_parent:any, _args:any, context: Context) => {\n            return context.prisma.category.findMany()\n        },\n        allProducts:(_parent:any, _args:any, context:Context) => {\n            return context.prisma.product.findMany()\n        },\n       productById:(_parent: any, {id}, context: Context) => {\n           return context.prisma.product.findUnique({\n               where: {\n                   id\n               }\n           })\n       },\n       categoryById:(_parent:any, {id}, context: Context) => {\n           return context.prisma.category.findUnique({\n               where: {\n                   id\n               }\n           })\n       },\n       productsByCategory:(_parent:any, {category}, context: Context) => {\n        return context.prisma.product.findMany({\n            select: {\n                category: true\n            }\n        })\n       }\n    },\n```\n\n```text\nmodel User {\n  id    Int    @id @default(autoincrement())\n  posts Post[]\n}\n\nmodel Post {\n  id        Int    @id @default(autoincrement())\n  authors   User[]\n}\n```\n\n```text\ntype User {\n  id: Int!\n  posts: [Post!]!\n}\n\n\ntype Post {\n  id: Int!\n  authors: [User!]!\n}\n```\n\n```text\nconst resolvers = {\n  Post: {\n    author: (parent, _args, context: Context) => {\n      return context.prisma.post\n        .findUnique({\n          where: { id: parent?.id },\n        })\n        .authors()\n    },\n    },\n  User: {\n    posts: (parent, _args, context: Context) => {\n      return context.prisma.user\n        .findUnique({\n          where: { id: parent?.id },\n        })\n        .posts()\n    },\n  } \n}\n```\n\n```text\nschema.graphql\n```\n\n```text\nUser\n```\n\n```text\nPost\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":196,"estimatedTokens":954}}328{"id":"stack-71516445","source":"stackoverflow","questionId":71516445,"title":"How to sample a PostgreSQL database using Prisma?","tags":["postgresql","sampling","prisma"],"text":"Title: How to sample a PostgreSQL database using Prisma?\nTags: postgresql, sampling, prisma\nSource: Stack Overflow\n\nQuestion:\nSuppose I have several millions of statements in my PostgreSQL database and I want to get only 10000 of them. But not the first 10000, rather, a random selection of 10000 (it would be best if I could also choose the logic, e.g. select every 4th statement).\n\nHow could I do this using Prisma, or — if it's not possible using Prisma — using a good old PostgreSQL request?\n\nFor now, I'm using this code to limit the number of results I'm getting:\n\n```\nconst statements = await this.prisma.statement.findMany({\n where: {\n OR: conditions,\n },\n orderBy: {\n createdAt: 'asc',\n },\n take: 10000,\n });\n```\n\nThis will use the conditions I have, then order them in ascending order, and \"take\" or limit the first 10000 results.\n\nWhat could I use in place of the \"take\" or what request I could make directly in PostgreSQL to randomly sample my DB for records?\n\n========================================\n\nTop Answer:\nTo reiterate Nurul's response, this isn't supported in Prisma.\n\nIf you have some field that auto-increments like an `id` you could likely generate an array of randomly selected ids and then query for those. This may not be ideal for a larger sample of 100,000 or 1,000,000 but in the case of 100 to 10,000 I think this could be a viable fallback solution until functionality is supported\n\n```\nconst idsArray = [5, 9, 13, 2, 18]; // Random array of IDs\n\nconst statements = await this.prisma.statement.findMany({\n where: {\n id: {\n in: idsArray,\n },\n },\n});\n```\n\n========================================\n\nCode:\n```js\nconst statements = await this.prisma.statement.findMany({\n      where: {\n        OR: conditions,\n      },\n      orderBy: {\n        createdAt: 'asc',\n      },\n      take: 10000,\n    });\n```\n\n```text\nconst idsArray = [5, 9, 13, 2, 18]; // Random array of IDs\n\nconst statements = await this.prisma.statement.findMany({\n    where: {\n        id: {\n            in: idsArray,\n        },\n    },\n});\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Please have a look at `[this](https:&#47;&#47;stackoverflow.com&#47;questions&#47;8674718&#47;best-way-&zwnj;&#8203;to-select-random-row&zwnj;&#8203;s-postgresql)` post.\n- Thank you, @Nurul. Could you please tell me how I use the `random` function to retrieve the random 10000 from all the available records? This was not clear to me from the comment above. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":82,"estimatedTokens":618}}329{"id":"stack-69153512","source":"stackoverflow","questionId":69153512,"title":"Prisma: Error: P1017 Server has closed the connection","tags":["node.js","postgresql","graphql-js","prisma","prisma-graphql"],"text":"Title: Prisma: Error: P1017 Server has closed the connection\nTags: node.js, postgresql, graphql-js, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI have a prisma 2 project with nodejs server all things was working pefectly, and when I upgraded prisma from 2 to \"3.0.2\" version the `prisma db push` command no longer work and it throws this error:\n\n```\nError: P1017\nServer has closed the connection.\n```\n\nI am sure that the postgres database works because all queries and mutations requests are still working.\n\n========================================\n\nCode:\n```text\nError: P1017\nServer has closed the connection.\n```\n\n```text\nprisma db push\n```\n\n```text\nprisma db pull\n```\n\n```text\nprisma db push\n```\n\n========================================\n\nComments:\n- This is really weird, but worked","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":38,"estimatedTokens":200}}330{"id":"stack-74167803","source":"stackoverflow","questionId":74167803,"title":"How to create one to one relationship instead of one to many in Prisma","tags":["typescript","prisma"],"text":"Title: How to create one to one relationship instead of one to many in Prisma\nTags: typescript, prisma\nSource: Stack Overflow\n\nQuestion:\nI have these prisma models\n\n```\nmodel OrderDetail {\n id String @id @default(cuid())\n orderId String\n address String\n city String\n country String\n postalCode String\n phone String\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)\n}\n\nmodel Order {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n userId String \n orderItems OrderItem[]\n orderDetails OrderDetail[] // cant have no arrays\n}\n```\n\nif I remove the `[]` from `orderDetails OrderDetail[]` I get the following type error in the `order @relation` from `OrderDetail`\n\nError parsing attribute \"@relation\": The relation field `order` on\nModel `OrderDetail` must not specify the `onDelete` or `onUpdate`\nargument in the @relation attribute. You must only specify it on the\nopposite field `orderDetails` on model `Order`.\n\nAfter removing the `onDelete: Cascade` from `order @relation` the error is this one\n\nError parsing attribute \"@relation\": The relation field `order` on\nModel `OrderDetail` is required. This is no longer valid because it's\nnot possible to enforce this constraint on the database level. Please\nchange the field type from `Order` to `Order?` to fix this.\n\nI only want to have one-to-one relationship there, not one to many.\n\nHow to fix?\n\n========================================\n\nCode:\n```text\nmodel OrderDetail {\n    id        String @id @default(cuid())\n    orderId   String\n    address   String\n    city      String\n    country   String\n    postalCode String\n    phone     String\n    createdAt DateTime @default(now())\n    updatedAt DateTime @updatedAt\n    order     Order   @relation(fields: [orderId], references: [id], onDelete: Cascade)\n}\n\nmodel Order {\n    id          String   @id @default(cuid())\n    createdAt   DateTime @default(now())\n    updatedAt   DateTime @updatedAt\n    user        User     @relation(fields: [userId], references: [id], onDelete: Cascade)\n    userId      String   \n    orderItems  OrderItem[]\n    orderDetails OrderDetail[] // cant have no arrays\n}\n```\n\n```text\n[]\n```\n\n```text\norderDetails OrderDetail[]\n```\n\n```text\norder @relation\n```\n\n```text\nOrderDetail\n```\n\n```text\norder\n```\n\n```text\nOrderDetail\n```\n\n```text\nonDelete\n```\n\n```text\nonUpdate\n```\n\n```text\norderDetails\n```\n\n```text\nOrder\n```\n\n```text\nonDelete: Cascade\n```\n\n```text\norder @relation\n```\n\n```text\norder\n```\n\n```text\nOrderDetail\n```\n\n```text\nOrder\n```\n\n```text\nOrder?\n```\n\n```text\norderId\n```\n\n```text\n@unique\n```\n\n```text\nOrder\n```\n\n```text\nOrderDetail\n```\n\n```text\nunique\n```\n\n```text\nOrderDetail\n```\n\n```text\norderId\n```\n\n========================================\n\nComments:\n- Have you tried the first error's suggestion of \"You must only specify it on the opposite field orderDetails on model Order.\"?\n- Yes, I've tried removing the `order @relation` from the `OrderDetail` model and adding a `orderDetails @relation` in `Order`, and also leaving them both added with similar results.\n- Thanks, I already had to make the `OrderDetail?` optional in the `Order` model. But you saved me.\n- I also had to add an `orderDetailId String? @unique` to the `Order` model.","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":177,"estimatedTokens":849}}331{"id":"stack-69490891","source":"stackoverflow","questionId":69490891,"title":"Workouts App Schema for MySQL using Prisma","tags":["mysql","database-design","database-schema","prisma"],"text":"Title: Workouts App Schema for MySQL using Prisma\nTags: mysql, database-design, database-schema, prisma\nSource: Stack Overflow\n\nQuestion:\nI am creating a workout app using MySQL and Prisma, and I am struggling to design a schema for the data.\n\nThe app will have users and workout programs. For example a workout program 'Get Jacked', could consist of 3 blocks (each block is 1 month). Each block will contain 5 workouts per week, each workout will contain multiple exercises and a warm up. Some important things to note: each User should be able to record their personal sets and reps for each exercise within a workout. They should also be able to complete a program ('Get Jacked'), as many times as they like and each time they should be able to record new values for their reps and sets.\n\nHere's my models so far:\n\n```\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n name String?\n role Role @default(USER)\n workouts Workout[]\n}\n\nmodel Program {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n name String\n published Boolean @default(false)\n author User @relation(fields: [authorId], references: [id])\n authorId Int\n}\n\nmodel Block {\n id Int @id @default(autoincrement())\n name String\n program Program @relation(fields: [programId], references: [id])\n programId Int\n}\n\nmodel Workout {\n id Int @id @default(autoincrement())\n name String\n week String\n day String\n block Block @relation(fields: [blockId], references: [id])\n blockId Int\n}\n\nmodel WorkoutSet {\n id Int @id @default(autoincrement())\n name String\n sets Int\n reps Int\n workout Workout @relation(fields: [workoutId], references: [id])\n workoutId Int\n exercise Exercise @relation(fields: [exerciseId], references: [id])\n exerciseId Int\n}\n\nmodel Exercise {\n id Int @id @default(autoincrement())\n name String\n}\n\nmodel LogWorkout {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n workout Workout @relation(fields: [workoutId], references: [id])\n workoutId Int\n}\n\nmodel LogWorkoutSet {\n id Int @id @default(autoincrement())\n createdAt DateTime @default(now())\n sets Int\n reps Int\n weight Int\n logWorkout LogWorkout @relation(fields: [logWorkoutId], references: [id])\n logWorkoutId Int\n workoutSet User @relation(fields: [workoutSetId], references: [id])\n workoutSetId Int\n}\n```\n\nI am relatively new to relational databases and what I can't seem to get my head around is how the recording of the reps ties back to the user and how the user can complete the workout program multiple times.\n\nAny help would be much appreciated.\n\nThanks,\nAdam\n\n========================================\n\nCode:\n```text\nmodel User {\n  id      Int      @id @default(autoincrement())\n  email   String   @unique\n  name    String?\n  role    Role     @default(USER)\n  workouts   Workout[]\n}\n\nmodel Program {\n  id         Int        @id @default(autoincrement())\n  createdAt  DateTime   @default(now())\n  name       String\n  published  Boolean    @default(false)\n  author     User       @relation(fields: [authorId], references: [id])\n  authorId   Int\n}\n\nmodel Block {\n  id         Int        @id @default(autoincrement())\n  name       String\n  program    Program    @relation(fields: [programId], references: [id])\n  programId  Int\n}\n\nmodel Workout {\n  id         Int        @id @default(autoincrement())\n  name       String\n  week       String\n  day        String\n  block      Block    @relation(fields: [blockId], references: [id])\n  blockId    Int\n}\n\nmodel WorkoutSet {\n  id         Int        @id @default(autoincrement())\n  name       String\n  sets       Int\n  reps       Int\n  workout    Workout   @relation(fields: [workoutId], references: [id])\n  workoutId  Int\n  exercise   Exercise   @relation(fields: [exerciseId], references: [id])\n  exerciseId Int\n}\n\nmodel Exercise {\n  id         Int        @id @default(autoincrement())\n  name       String\n}\n\nmodel LogWorkout {\n  id         Int        @id @default(autoincrement())\n  createdAt  DateTime   @default(now())\n  workout    Workout    @relation(fields: [workoutId], references: [id])\n  workoutId  Int\n}\n\nmodel LogWorkoutSet {\n  id         Int        @id @default(autoincrement())\n  createdAt  DateTime   @default(now())\n  sets       Int\n  reps       Int\n  weight     Int\n  logWorkout LogWorkout @relation(fields: [logWorkoutId], references: [id])\n  logWorkoutId   Int\n  workoutSet     User       @relation(fields: [workoutSetId], references: [id])\n  workoutSetId   Int\n}\n```\n\n```text\n// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\nmodel User {\n  id             Int              @id @default(autoincrement())\n  email          String           @unique\n  name           String?\n  role           Role             @default(USER)\n  programs       Program[]\n  programRecords ProgramRecord[]\n  exercises      ExerciseRecord[]\n}\n\n// Programs available\nmodel Program {\n  id        Int             @id @default(autoincrement())\n  name      String\n  published Boolean         @default(false)\n  authorId  Int\n  author    User            @relation(fields: [authorId], references: [id])\n  blocks    Block[]\n  records   ProgramRecord[]\n  createdAt DateTime        @default(now())\n}\n\n// Blocks within a program\nmodel Block {\n  id        Int       @id @default(autoincrement())\n  name      String\n  programId Int\n  program   Program   @relation(fields: [programId], references: [id])\n  workouts  Workout[]\n}\n\n// Workouts within a block\nmodel Workout {\n  id        Int                 @id @default(autoincrement())\n  name      String\n  week      String\n  day       String\n  blockId   Int\n  block     Block               @relation(fields: [blockId], references: [id])\n  exercises ExerciseOnWorkout[]\n}\n\n// Exercises to be done in workout (Relation table)\nmodel ExerciseOnWorkout {\n  id         Int              @id @default(autoincrement())\n  workoutId  Int\n  workout    Workout          @relation(fields: [workoutId], references: [id])\n  exerciseId Int\n  exercise   Exercise         @relation(fields: [exerciseId], references: [id])\n  name       String\n  sets       Int\n  reps       Int\n  weight     Int\n  records    ExerciseRecord[]\n  createdAt  DateTime         @default(now())\n\n  // Restrict to do not repeat combinations with same name\n  @@unique([workoutId, exerciseId, name])\n}\n\n// Exercise options\nmodel Exercise {\n  id       Int                 @id @default(autoincrement())\n  name     String\n  workouts ExerciseOnWorkout[]\n}\n\n// New \"enrollment\" record of a user in a program\nmodel ProgramRecord {\n  id              Int              @id @default(autoincrement())\n  programId       Int\n  program         Program          @relation(fields: [programId], references: [id])\n  userId          Int\n  user            User             @relation(fields: [userId], references: [id])\n  exerciseRecords ExerciseRecord[]\n  // TODO: You could track the status to prevent users starting a new one\n  isComplete      Boolean          @default(false)\n  createdAt       DateTime         @default(now())\n}\n\n// User personal record for a workout exercise\nmodel ExerciseRecord {\n  id              Int               @id @default(autoincrement())\n  userId          Int\n  user            User              @relation(fields: [userId], references: [id])\n  exerciseId      Int\n  exercise        ExerciseOnWorkout @relation(fields: [exerciseId], references: [id])\n  programRecordId Int\n  programRecord   ProgramRecord     @relation(fields: [programRecordId], references: [id])\n  name            String\n  sets            Int\n  reps            Int\n  weight          Int\n  createdAt       DateTime          @default(now())\n\n  @@unique([userId, exerciseId, programRecordId, name])\n}\n\nenum Role {\n  USER\n}\n```\n\n========================================\n\nComments:\n- Thanks Victor, appreciate your help. Do you know if a one to many relationship can be created from a relation table?","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":281,"estimatedTokens":1997}}332{"id":"stack-68108134","source":"stackoverflow","questionId":68108134,"title":"Prisma.js - How to insert into table that has many-to-many relationship","tags":["node.js","database","orm","prisma","prisma2"],"text":"Title: Prisma.js - How to insert into table that has many-to-many relationship\nTags: node.js, database, orm, prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nHow can I assign some tags to the post using Prisma.js?\n\nI have some tags already and I want to assign some tags to the post?\nI don't want to create a new tag.\n\n**schema.prisma:**\n\n```\nmodel Post {\n Id String @id @default(uuid())\n AuthorId String\n Author User @relation(fields: [AuthorId], references: [Id])\n CategoryId String?\n Category Category? @relation(fields: [CategoryId], references: [Id])\n Title String @db.VarChar(255)\n Description String? @db.MediumText\n Summary String? @db.VarChar(255)\n\n Tags TagPostMapping[]\n}\n\nmodel TagPostMapping {\n Id String @id @default(uuid())\n Post Post? @relation(fields: [PostId], references: [Id])\n PostId String?\n Tag Tag? @relation(fields: [TagId], references: [Id])\n TagId String?\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime? @updatedAt\n}\n\nmodel Tag {\n Id String @id @default(uuid())\n Title String @unique\n Posts TagPostMapping[]\n CreatedDate DateTime @default(now())\n ModifiedDate DateTime? @updatedAt\n}\n```\n\nIn the Prisma website, there is an example but it's suitable for creating some tags and assign them to the Post.\nWhile I want to add some of the existing tags to the article.\n\nhttps://www.prisma.io/docs/support/help-articles/working-with-many-to-many-relations#explicit-relations\n\n========================================\n\nTop Answer:\nI had a similar situation and the below code worked for me:\n\n```\naddTagToPost(addTagDto: AddTagDto): Promise {\n return prisma.tag.update({\n where: { Id: addTagDto.tagId },\n data: {\n Posts: {\n create: [\n {\n Post: {\n connect: {\n Id: addTagDto.postId,\n },\n },\n },\n ],\n },\n },\n });\n }\n```\n\nPS: As `Post` and `Tag` have a many-to-many relationship, you can update `prisma.post.update` as well.\n\n========================================\n\nCode:\n```text\nmodel Post {\n  Id                 String           @id @default(uuid())\n  AuthorId           String\n  Author             User             @relation(fields: [AuthorId], references: [Id])\n  CategoryId         String?\n  Category           Category?        @relation(fields: [CategoryId], references: [Id])\n  Title              String           @db.VarChar(255)\n  Description        String?          @db.MediumText\n  Summary            String?          @db.VarChar(255)\n\n  Tags               TagPostMapping[]\n}\n\nmodel TagPostMapping {\n  Id           String     @id @default(uuid())\n  Post         Post?      @relation(fields: [PostId], references: [Id])\n  PostId       String?\n  Tag          Tag?       @relation(fields: [TagId], references: [Id])\n  TagId        String?\n  CreatedDate  DateTime   @default(now())\n  ModifiedDate DateTime?  @updatedAt\n}\n\nmodel Tag {\n  Id             String           @id @default(uuid())\n  Title          String           @unique\n  Posts          TagPostMapping[]\n  CreatedDate    DateTime         @default(now())\n  ModifiedDate   DateTime?        @updatedAt\n}\n```\n\n```text\npublic async Create(post: IPost): Promise<Post> {\n\n    let postId = v4();\n    let postTagIds: postTagMapping[] = [];\n    post.Tags?.map(tag => postTagIds.push({ PostId: postId, TagId: tag.Id }));\n\n    const transResult = await ApplicationDbContext.Prisma.$transaction([\n      ApplicationDbContext.Prisma.post.create({\n        data: {\n          Id: postId,\n          Title: post.Title,\n          Summary: post.Summary,\n          Description: post.Description,\n          IsActive: post.IsActive,\n          IsPublished: post.IsPublished,\n          IsActiveNewComment: post.IsActiveNewComment,\n          AuthorId: post.AuthorId,\n          CategoryId: post.CategoryId,\n        },\n      }),\n      ApplicationDbContext.Prisma.tagPostMapping.createMany({\n        data: postTagIds\n      })\n\n    ]).finally(async () => {\n      await ApplicationDbContext.Prisma.$disconnect();\n    });\n\n    let result = transResult as unknown as Post;\n\n    return result;\n  }\n```\n\n```text\n$transaction\n```\n\n```text\npostId = v4()\n```\n\n```text\nv4()\n```\n\n```text\nuuid\n```\n\n```text\nId\n```\n\n```text\naddTagToPost(addTagDto: AddTagDto): Promise<TagDto> {\n    return prisma.tag.update({\n      where: { Id: addTagDto.tagId },\n      data: {\n        Posts: {\n          create: [\n            {\n              Post: {\n                connect: {\n                  Id: addTagDto.postId,\n                },\n              },\n            },\n          ],\n        },\n      },\n    });\n  }\n```\n\n```text\nPost\n```\n\n```text\nTag\n```\n\n```text\nprisma.post.update\n```\n\n```text\nawait prisma.post.create({\n      data: {\n          tags: {\n            create: [\n              { \n                tag: \n                { \n                  connectOrCreate: \n                  { \n                     where: {\n                      name: 'dev' \n                     },\n                     create: {\n                      name: 'dev'\n                    },\n                  } \n                } \n              },\n            ],\n          },\n```\n\n```text\nawait prisma.post.update({\n    where: {\n        id: \"idpost\"\n      },\n      data: {\n       ...\n       //same with code above\n      }\n```","metadata":{"transformedAt":"2026-08-18T18:33:14.852Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":235,"estimatedTokens":1285}}333{"id":"stack-70792419","source":"stackoverflow","questionId":70792419,"title":"Accessing models by using a variable","tags":["prisma"],"text":"Title: Accessing models by using a variable\nTags: prisma\nSource: Stack Overflow\n\nQuestion:\nHow can I **dynamically** access a **model** in prisma?\n\n```\nreturn await prisma[modelName].create({ data })\n```\n\n*... seems not to work.*\n\nI am looking for a way to access my models by using a variable. How can this be done?\n\n**Update:**\n\nThere is a typescript error: `Unable to compile TypeScript`.\n\n```\nerror TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PrismaClient'.\n No index signature with a parameter of type 'string' was found on type 'PrismaClient'.\n```\n\n========================================\n\nTop Answer:\n```\ntype modelName = Uncapitalize \nconst key = \"someTable\" as modelName \nconst result = await db[key].findMany()\n```\n\n========================================\n\nCode:\n```text\nreturn await prisma[modelName].create({ data })\n```\n\n```text\nerror TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.\n  No index signature with a parameter of type 'string' was found on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.\n```\n\n```text\nUnable to compile TypeScript\n```\n\n```js\n// @ts-ignore\nreturn await prisma[modelName].create({ data });\n```\n\n```text\n// @ts-ignore\n```\n\n```js\ntype modelName = Uncapitalize<Prisma.ModelName>  \nconst key = \"someTable\" as modelName  \nconst result = await db[key].findMany()\n```\n\n========================================\n\nComments:\n- \"Not to work\" in what way? Is there some error? Could you clarify what happens?\n- This doesn't fully answer your question, but you can get rid of the `string` type by replacing it with `type ModelName = Uncapitalize` (importing `import { Prisma } from \"@prisma&#47;client\"`). You will still get an error if you try creating a new object with `prisma[myModelName].create`: `Each member of the union type ... has signatures, but none of those signatures are compatible with each other.\"`\n- @Danila I am not the OP, but for me it just doesn't do anything. But I am using this to access a field, not a model. Prisma doesn't throw errors. And the field doesn't get changed. Just nothing happens. Code gets executed as if it were OK.\n- This might be a bit old, but this one worked for me.\n- As long as *modelName* is a **lowerCamelCase** string representing a valid model name, the `&#47;&#47;@ts-ignore` is not required as the variable it is accepted.","metadata":{"transformedAt":"2026-08-18T18:33:14.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":72,"estimatedTokens":644}}334{"id":"stack-68432776","source":"stackoverflow","questionId":68432776,"title":"count self relation on Prisma error: table name specified more than once","tags":["prisma","prisma2"],"text":"Title: count self relation on Prisma error: table name specified more than once\nTags: prisma, prisma2\nSource: Stack Overflow\n\nQuestion:\nI am trying to count a self relation (followers) in Prisma2 (using PostgreSQL)\n\nModel:\n\n```\nmodel User {\n id String @id @default(cuid())\n following User[] @relation(name: \"UserFollows\")\n followers User[] @relation(name: \"UserFollows\")\n}\n```\n\nQuery:\n\n```\nconst user = await prisma.user.findUnique({\n where: { id: userId },\n include: {\n _count: {\n select: { followers: true, following: true },\n },\n },\n});\n```\n\n(using `previewFeatures = [\"selectRelationCount\"]`) and getting the following error:\n\nInvalid `prisma.user.findUnique()` invocation:\n\nError occurred during query execution: ConnectorError(ConnectorError\n{ user_facing_error: None, kind: QueryError(Error { kind: Db, cause:\nSome(DbError { severity: \"ERROR\", parsed_severity: Some(Error), code:\nSqlState(\"42712\"), message: \"table name \"User\" specified more than\nonce\", detail: None, hint: None, position: None, where_: None, schema:\nNone, table: None, column: None, datatype: None, constraint: None,\nfile: Some(\"parse_relation.c\"), line: Some(423), routine:\nSome(\"checkNameSpaceConflicts\") }) }) })\n\nDoes anybody have any idea of what I am doing wrong?\n\n========================================\n\nTop Answer:\nit's a bit late but for whoever may get stuck later yo can do something like this\n\n```\nconst user = await prisma.user.findUnique({ \n where: { id: userId },\n include: {\n _count: true,\n },\n});\n```\n\nthis should output something like this\n\n```\n//user data\n\"_count\": {\n \"followers\": 99,\n \"following\": 99\n }\n```\n\nyou can then add them in your frontend\n\n========================================\n\nCode:\n```text\nmodel User {\n  id        String  @id @default(cuid())\n  following User[]  @relation(name: \"UserFollows\")\n  followers User[]  @relation(name: \"UserFollows\")\n}\n```\n\n```text\nconst user = await prisma.user.findUnique({\n  where: { id: userId },\n  include: {\n    _count: {\n      select: { followers: true, following: true },\n    },\n  },\n});\n```\n\n```text\npreviewFeatures = [\"selectRelationCount\"]\n```\n\n```text\nprisma.user.findUnique()\n```\n\n```js\nconst user = await prisma.user.findUnique({\n        where: {\n            id: userId,\n        },\n        include: {\n            followers: true,\n            following: true,\n        },\n    });\n    let followerCount = user.followers.length; \n    let followingCount = user.following.length;\n```\n\n```js\n// number of followers for some user \"x\" = number of times x.id appaers in \"following\" relation of other users.\n    const followerCount = await prisma.user.count({\n        where: {\n            following: {\n                some: {\n                    id: userId,\n                },\n            },\n        },\n    });\n\n// number of users that user \"x\" is following = number of times x.id appaers in \"followers\" relation of other users.\n    const followingCount = await prisma.user.count({\n        where: {\n            followers: {\n                some: {\n                    id: userId,\n                },\n            },\n        },\n    });\n```\n\n```text\nmodel Follows {\n  follower    User @relation(\"follower\", fields: [followerId], references: [id])\n  followerId  String\n  following   User @relation(\"following\", fields: [followingId], references: [id])\n  followingId String\n\n  @@id([followerId, followingId])\n}\n\nmodel User {\n  id        String  @id @default(cuid())\n  followers Follows[] @relation(\"follower\")\n  following Follows[] @relation(\"following\")\n}\n```\n\n```text\nfollowers\n```\n\n```text\nfollowing\n```\n\n```text\ncount\n```\n\n```text\nfollowers\n```\n\n```text\nfollowing\n```\n\n```text\nconst user = await prisma.user.findUnique({ \n    where: { id: userId },\n    include: {\n        _count: true,\n    },\n});\n```\n\n```text\n//user data\n\"_count\": {\n    \"followers\": 99,\n    \"following\": 99\n }\n```\n\n========================================\n\nComments:\n- Will this count any relation? For example if I have another relation and I don't need to count it, will your solution include this as well?\n- yes if you only want followers for example you can do something like this _count: { select: { followers: true } } instead of _count: true","metadata":{"transformedAt":"2026-08-18T18:33:14.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":198,"estimatedTokens":1040}}335{"id":"stack-55409155","source":"stackoverflow","questionId":55409155,"title":"Prisma Connection WhereInput for Array of enum values?","tags":["javascript","graphql","prisma","prisma-graphql","graphql-tag"],"text":"Title: Prisma Connection WhereInput for Array of enum values?\nTags: javascript, graphql, prisma, prisma-graphql, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nDoing this 👇\n\n```\nquery {\n postsConnection(where: {\n status: PUBLISHED\n }) {\n aggregate {\n count\n }\n edges {\n cursor\n node {\n id\n slug\n }\n }\n }\n}\n```\n\ngives me `postsConnection` of published posts.\n\nThe `Post` model has an array of `Category` enum in field `categories`. This is the Post in `datamodel` 👇\n\n```\nenum Category {\n TECH\n FIN\n DIGIMARK\n CODING\n TUTORIAL\n HOWTO\n WRITING\n INSPIRE\n SCIENCE\n POLITICS\n LIFESTYLE\n}\ntype Post {\n id: ID!\n title: String!\n editorSerializedOutput: Json!\n editorCurrentContent: Json!\n editorHtml: String!\n updatedAt: DateTime!\n createdAt: DateTime!\n author: User\n authorId: String!\n categories: [Category!]!\n thumbnail: Json!\n status: PostStatus!\n slug: String!\n}\n```\n\n***My question is, what Prisma Query do I need to write to get `PostConnection` of posts in a specific category?***\n\n========================================\n\nCode:\n```text\nquery {\n  postsConnection(where: {\n    status: PUBLISHED\n  }) {\n    aggregate {\n      count\n    }\n    edges {\n      cursor\n      node {\n        id\n        slug\n      }\n    }\n  }\n}\n```\n\n```text\nenum Category {\n  TECH\n  FIN\n  DIGIMARK\n  CODING\n  TUTORIAL\n  HOWTO\n  WRITING\n  INSPIRE\n  SCIENCE\n  POLITICS\n  LIFESTYLE\n}\ntype Post {\n  id: ID!\n  title: String!\n  editorSerializedOutput: Json!\n  editorCurrentContent: Json!\n  editorHtml: String!\n  updatedAt: DateTime!\n  createdAt: DateTime!\n  author: User\n  authorId: String!\n  categories: [Category!]!\n  thumbnail: Json!\n  status: PostStatus!\n  slug: String!\n}\n```\n\n```text\npostsConnection\n```\n\n```text\nPost\n```\n\n```text\nCategory\n```\n\n```text\ncategories\n```\n\n```text\ndatamodel\n```\n\n```text\nPostConnection\n```\n\n```text\nto-many\n```\n\n```text\nCategory\n```\n\n========================================\n\nComments:\n- You already filter posts in your connection using `status: PUBLISHED`, you can do the same with `categories`\n- That's what the question is. I cannot do that with categories.. it is an array\n- Oh sorry, didn't quite understood the question, I added a better answer","metadata":{"transformedAt":"2026-08-18T18:33:14.853Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":154,"estimatedTokens":539}}336{"id":"stack-50597433","source":"stackoverflow","questionId":50597433,"title":"Not able to run prisma deploy: Error: Cluster undefined does not exist","tags":["graphql","graphql-js","prisma","prisma-graphql"],"text":"Title: Not able to run prisma deploy: Error: Cluster undefined does not exist\nTags: graphql, graphql-js, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am learning graphql and following this tutorial https://www.howtographql.com/react-apollo/1-getting-started/\n\ni have installed prisma using `npm install -g prisma` and while running this command `prisma deploy` in server folder iam getting this error:\n\n```\nconfig CWD /Users/aravind/tekie/hackernews-react-apollo/server +0ms\n config HOME /Users/aravind +2ms\n config definitionDir /Users/aravind/tekie/hackernews-react-apollo/server/database +5ms\n config definitionPath /Users/aravind/tekie/hackernews-react-apollo/server/database/prisma.yml +0ms\n cli { isGlobal: true } +0ms\n StatusChecker setting status checker +0ms\n cli command id deploy +7ms\n cli:plugincache Got plugin from cache +0ms\n cli:plugincache /Users/aravind/Library/Caches/prisma/plugins.json +1ms\n cli:plugincache Got plugin from cache +1ms\n cli:plugincache /Users/aravind/Library/Caches/prisma/plugins.json +0ms\n plugins findCommand prisma-cli-core +0ms\n plugin requiring command +0ms\n cli-engine:plugins:manager requiring /usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core +0ms\n portfinder:defaultHosts exports._defaultHosts is: [ '0.0.0.0', '127.0.0.1', '::1', 'fe80::1', 'fe80::18fb:a4af:2b44:3fea', '192.168.43.100', '2405:204:6209:18b0:144f:bac3:86ac:3cdf', '2405:204:6209:18b0:fd46:e3b7:952f:d569', 'fe80::1c49:3cff:fe5f:7e16', 'fe80::3e5f:ab5d:16dd:a8bf' ] +0ms\n cli-engine:plugins:manager required +538ms\n plugin required command +540ms\n StatusChecker setting status checker +569ms\nError: Cluster undefined does not exist.\n at Deploy. (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/src/commands/deploy/index.ts:175:13)\n at step (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/dist/commands/deploy/index.js:42:23)\n at Object.next (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/dist/commands/deploy/index.js:23:53)\n at fulfilled (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/dist/commands/deploy/index.js:14:58)\n at \n util timed out +0ms\nExiting with code: 0\n```\n\nup to this all the set-up was correct and I am unable to run this command. Any help is appreciated.\n\n========================================\n\nTop Answer:\nCan you run with yarn prisma deploy after download yarn not using npm prisma deploy\n\n========================================\n\nCode:\n```text\nconfig CWD /Users/aravind/tekie/hackernews-react-apollo/server +0ms\n  config HOME /Users/aravind +2ms\n  config definitionDir /Users/aravind/tekie/hackernews-react-apollo/server/database +5ms\n  config definitionPath /Users/aravind/tekie/hackernews-react-apollo/server/database/prisma.yml +0ms\n  cli { isGlobal: true } +0ms\n  StatusChecker setting status checker +0ms\n  cli command id deploy +7ms\n  cli:plugincache Got plugin from cache +0ms\n  cli:plugincache /Users/aravind/Library/Caches/prisma/plugins.json +1ms\n  cli:plugincache Got plugin from cache +1ms\n  cli:plugincache /Users/aravind/Library/Caches/prisma/plugins.json +0ms\n  plugins findCommand prisma-cli-core +0ms\n  plugin requiring command +0ms\n  cli-engine:plugins:manager requiring /usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core +0ms\n  portfinder:defaultHosts exports._defaultHosts is: [ '0.0.0.0', '127.0.0.1', '::1', 'fe80::1', 'fe80::18fb:a4af:2b44:3fea', '192.168.43.100', '2405:204:6209:18b0:144f:bac3:86ac:3cdf', '2405:204:6209:18b0:fd46:e3b7:952f:d569', 'fe80::1c49:3cff:fe5f:7e16', 'fe80::3e5f:ab5d:16dd:a8bf' ] +0ms\n  cli-engine:plugins:manager required +538ms\n  plugin required command +540ms\n  StatusChecker setting status checker +569ms\nError: Cluster undefined does not exist.\n    at Deploy.<anonymous> (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/src/commands/deploy/index.ts:175:13)\n    at step (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/dist/commands/deploy/index.js:42:23)\n    at Object.next (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/dist/commands/deploy/index.js:23:53)\n    at fulfilled (/usr/local/lib/node_modules/prisma/node_modules/prisma-cli-core/dist/commands/deploy/index.js:14:58)\n    at <anonymous>\n  util timed out +0ms\nExiting with code: 0\n```\n\n```text\nnpm install -g prisma\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma version\n```\n\n```text\nnpm uninstall -g prisma\n```\n\n```text\nnpm install -g prisma@1.6.3\n```\n\n========================================\n\nComments:\n- Can you please additionally your `prisma.yml` file and the `~&#47;.prisma&#47;config.yml` file? **Please remove all sensitive information before sharing it here**. For example, the `config.yml` file contains a `cloudSessionKey` which shouldn't be shared.","metadata":{"transformedAt":"2026-08-18T18:33:14.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":101,"estimatedTokens":1194}}337{"id":"stack-52151398","source":"stackoverflow","questionId":52151398,"title":"yoga graphql server + prisma server : multitenancy","tags":["graphql","multi-tenant","prisma","prisma-graphql"],"text":"Title: yoga graphql server + prisma server : multitenancy\nTags: graphql, multi-tenant, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a backend env for multi-tenancy database using Prisma Server and Yoga GraphQL\n\nTo manage multi-tenancy, we choose to handle it by using the \"env\" (dev/stage/prod) of Prisma Server.\nIt's OK, Prisma server was not difficult to manage and now we have an endpoint for each tenant like: `http://localhost:4466/service/tenant/`\n\nAfter that, it was easy to extract *.graphql from Prisma using graphql get-schema.\n\nBut now, the difficulty is: how to set up a GraphQL Server for as many as service I need and tenant ?\n\nBased on different exmample / tuto / docs / ... I don't find the way to set up GraphQL Server in my index.js to say: listen on multiple URI and each URI have one prisma server connected.\n\nExample, I need:\n\nGraphQL Server endpoint `http://localhost:4000/service-1/client-1/` can be only request `http://localhost:4466/service-1/client-1/`\n\nand for `client-2` (second tenant) `http://localhost:4000/service-1/client-2/` can be only request `http://localhost:4466/service-1/client-2/`\n\nGraphQL Server seems can be started only one time per port (here 4000)\n\n[EDIT] Here a code to illustrate https://github.com/mouchimotte/prisma-yoga-multitenancy\n\n========================================\n\nTop Answer:\nIf you wish to use a shared database strategy, meaning, one database with tenant ID column, you can use this package:\nhttps://www.npmjs.com/package/node-express-multitenant\n\n========================================\n\nCode:\n```text\nhttp://localhost:4466/service/tenant/\n```\n\n```text\nhttp://localhost:4000/service-1/client-1/\n```\n\n```text\nhttp://localhost:4466/service-1/client-1/\n```\n\n```text\nclient-2\n```\n\n```text\nhttp://localhost:4000/service-1/client-2/\n```\n\n```text\nhttp://localhost:4466/service-1/client-2/\n```\n\n========================================\n\nComments:\n- If you need more details do not hesitate ;)\n- I have just found this library (npmjs.com/package/prisma-multi-tenant). I hope it helps\n- thanks a lot @rma ! I think this package can be ma solution but I've stop dev using Prisma. I use Laravel instead, surely more longer to have the first query operational but more easy and structured ! More in adequateness with my product finally\n- Hello Errorname ! Like I've respond to @rma, I've stop dev using Prisma then pass to Laravel instead using \"laravel tenancy\" (hyn/multi-tenant) and folklore/graphql for the graphql part (who is based on webonyx package)","metadata":{"transformedAt":"2026-08-18T18:33:14.853Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":66,"estimatedTokens":635}}338