返回 Discover
Field DispatchStack Overflow10 · 2026-05-29

Prisma: Is there any way to execute javascript as default value of prisma data type?

Tags
javascriptgraphqlgraphql-jsprismaprisma-graphql
Score
5
Answers
1
Views
1,122
Answered
No
痛点分析发布于 2026/05/28

痛点为 AI 基于上游原始证据的初步提炼;未包含额外中国市场检索。

痛点

用户在使用 Prisma 定义数据模型时,希望为 ID 字段设置一个以用户前缀开头的动态默认值(如 `user--rear33422qeqr`),但 Prisma 的 `@default()` 属性不支持执行 JavaScript 函数或字符串插值。现有解决方案要么依赖数据库级别的触发器,要么使用已弃用的 Prisma 中间件,或者需要从头编写自定义 Prisma Client 扩展,这些方法都增加了开发复杂度和维护成本。用户不得不寻找变通方案,导致开发效率降低,且容易引入错误或不一致。

§ Dossier

Stack Overflow question

in my data model, as the type of id, I want to generate a default value that will start with the user. so the id will bed something like this user..rear33422qeqr type User { myId: String! @default (`user${2+2}`) name: String! email: String! @unique } is it possible to call a javascript function or using string interpolation ( user${2+2} )

§ Dossier

Question details

View count
1,122
Answer count
1
Last activity
2026/05/28
§ Dossier

Answers

While this is an older question, Prisma still does not natively support executing JavaScript functions inside the @default() attribute. To achieve this, developers typically have to rely on database-level triggers, deprecated Prisma middlewares, or write custom Prisma Client Extensions from scratch. To simplify this process, I created prisma-js-defaults — a zero-dependency Prisma extension that handles dynamic defaults out of the box. Key Advantages: Schema-driven: You declare the target function directly in your schema.prisma using a /// @defaultJs(fnName) comment. Runtime Execution: It executes your custom JS/TS functions on the client side before the query hits the database. Deep Traversal: It automatically handles nested relational writes ( create , createMany , connectOrCreate , and upsert ). Zero Dependencies & Prototype Safe. Usage Example: To achieve the user-- format you mentioned: 1. Update your schema.prisma : model User { // Use a standard default to satisfy TS, but override it with the custom decorator /// @defaultJs(generateUserId) myId String @id @default("") name String email String @unique } 2. Setup your Prisma Client: import { PrismaClient } from '@prisma/client'; import { withJsDefaults } from 'prisma-js-defaults'; import { jsDefaultsConfig } from './prisma/generated/js-defaults'; const prisma = new PrismaClient().$extends( withJsDefaults(jsDefaultsConfig, { generateUserId: () => `user--${Math.random().toString(36).substring(2, 10)}` }) ); You can find the setup instructions and source code here: NPM: https://www.npmjs.com/package/prisma-js-defaults GitHub: https://github.com/HokaigoTwin/prisma-js-defaults Disclaimer: I am the author of this package. I built it because I was facing the exact same limitations described in this thread and couldn't find a clean workaround. If anyone tries it out, I would genuinely appreciate your feedback on whether it fully covers your use cases!

评论作者信息不可用-1 votes
源数据· Raw Archive
source
Stack Overflow
upstream_source
stackoverflow
upstream_item_id
61585219
daily_ranking_item_id
3fb11e78-e6cf-45e2-aace-d3c18da66435
rank_date
2026-05-29
rank
10
name
Prisma: Is there any way to execute javascript as default value of prisma data type?
tagline
javascript, graphql, graphql-js, prisma, prisma-graphql
description
in my data model, as the type of id, I want to generate a default value that will start with the user. so the id will bed something like this user..rear33422qeqr type User { myId: String! @default (`user${2+2}`) name: String! email: String! @unique } is it possible to call a javascript function or using string interpolation ( user${2+2} )
votes_count
5
comments_count
1
created_at_on_source
2020-05-04T04:31:19.000Z
topics
javascriptgraphqlgraphql-jsprismaprisma-graphql
media / source-specific data
{
  "stackoverflow": {
    "score": 5,
    "view_count": 1122,
    "is_answered": false,
    "top_answers": [
      {
        "body": "While this is an older question, Prisma still does not natively support executing JavaScript functions inside the @default() attribute. To achieve this, developers typically have to rely on database-level triggers, deprecated Prisma middlewares, or write custom Prisma Client Extensions from scratch. To simplify this process, I created prisma-js-defaults — a zero-dependency Prisma extension that handles dynamic defaults out of the box. Key Advantages: Schema-driven: You declare the target function directly in your schema.prisma using a /// @defaultJs(fnName) comment. Runtime Execution: It executes your custom JS/TS functions on the client side before the query hits the database. Deep Traversal: It automatically handles nested relational writes ( create , createMany , connectOrCreate , and upsert ). Zero Dependencies & Prototype Safe. Usage Example: To achieve the user--<random> format you mentioned: 1. Update your schema.prisma : model User { // Use a standard default to satisfy TS, but override it with the custom decorator /// @defaultJs(generateUserId) myId String @id @default(\"\") name String email String @unique } 2. Setup your Prisma Client: import { PrismaClient } from '@prisma/client'; import { withJsDefaults } from 'prisma-js-defaults'; import { jsDefaultsConfig } from './prisma/generated/js-defaults'; const prisma = new PrismaClient().$extends( withJsDefaults(jsDefaultsConfig, { generateUserId: () => `user--${Math.random().toString(36).substring(2, 10)}` }) ); You can find the setup instructions and source code here: NPM: https://www.npmjs.com/package/prisma-js-defaults GitHub: https://github.com/HokaigoTwin/prisma-js-defaults Disclaimer: I am the author of this package. I built it because I was facing the exact same limitations described in this thread and couldn't find a clean workaround. If anyone tries it out, I would genuinely appreciate your feedback on whether it fully covers your use cases!",
        "score": -1,
        "answer_id": 79948010,
        "is_accepted": false
      }
    ],
    "answer_count": 1,
    "accepted_answer_id": null,
    "last_activity_date": 1779993985
  }
}
raw_payload
{
  "stats": {
    "score": 5,
    "view_count": 1122,
    "is_answered": false,
    "answer_count": 1,
    "creation_date": 1588566679,
    "last_edit_date": null,
    "accepted_answer_id": null,
    "last_activity_date": 1779993985
  },
  "api_wrapper": {
    "backoff": null,
    "has_more": true,
    "page_size": 8,
    "quota_max": 300,
    "quota_remaining": 294
  },
  "question_id": 61585219,
  "answer_fetch": {
    "has_more": false,
    "answers_fetched": 1,
    "answer_page_size": 3
  },
  "snapshot_version": "stackoverflow_question_v1"
}
source_raw_snapshot
{
  "id": "0270e3f4-f92c-4cdb-936f-0eb30e297fdf",
  "daily_ranking_item_id": "3fb11e78-e6cf-45e2-aace-d3c18da66435",
  "source": "stackoverflow",
  "external_id": "61585219",
  "fetched_at": "2026-05-28T22:02:15.509Z",
  "question_raw": {
    "body": "<p>in my data model, as the type of id, I want to generate a default value that will start with the user.</p>\n\n<p>so the id will bed something like this <code>user..rear33422qeqr</code></p>\n\n<pre><code>type User {\n\n  myId: String! @default (`user${2+2}`)\n  name: String!\n  email: String! @unique\n\n}\n</code></pre>\n\n<p>is it possible to call a javascript function or using string interpolation (<code>user${2+2}</code>)</p>\n",
    "link": "https://stackoverflow.com/questions/61585219/prisma-is-there-any-way-to-execute-javascript-as-default-value-of-prisma-data-t",
    "tags": [
      "javascript",
      "graphql",
      "graphql-js",
      "prisma",
      "prisma-graphql"
    ],
    "owner": {
      "link": "https://stackoverflow.com/users/5534469/ashik",
      "user_id": 5534469,
      "user_type": "registered",
      "account_id": 7255753,
      "reputation": 3508,
      "display_name": "Ashik",
      "profile_image": "https://www.gravatar.com/avatar/c100d4bf62af61c3cce61692945b8c4d?s=256&d=identicon&r=PG&f=y&so-version=2"
    },
    "score": 5,
    "title": "Prisma: Is there any way to execute javascript as default value of prisma data type?",
    "view_count": 1122,
    "is_answered": false,
    "question_id": 61585219,
    "answer_count": 1,
    "creation_date": 1588566679,
    "content_license": "CC BY-SA 4.0",
    "last_activity_date": 1779993985
  },
  "answers_raw": [
    {
      "body": "<p>While this is an older question, Prisma still does not natively support executing JavaScript functions inside the <code>@default()</code> attribute. To achieve this, developers typically have to rely on database-level triggers, deprecated Prisma middlewares, or write custom Prisma Client Extensions from scratch.</p>\n<p>To simplify this process, I created <strong><a href=\"https://www.npmjs.com/package/prisma-js-defaults\" rel=\"nofollow noreferrer\">prisma-js-defaults</a></strong> — a zero-dependency Prisma extension that handles dynamic defaults out of the box.</p>\n<h3>Key Advantages:</h3>\n<ul>\n<li><strong>Schema-driven:</strong> You declare the target function directly in your <code>schema.prisma</code> using a <code>/// @defaultJs(fnName)</code> comment.</li>\n<li><strong>Runtime Execution:</strong> It executes your custom JS/TS functions on the client side <em>before</em> the query hits the database.</li>\n<li><strong>Deep Traversal:</strong> It automatically handles nested relational writes (<code>create</code>, <code>createMany</code>, <code>connectOrCreate</code>, and <code>upsert</code>).</li>\n<li><strong>Zero Dependencies &amp; Prototype Safe.</strong></li>\n</ul>\n<h3>Usage Example:</h3>\n<p>To achieve the <code>user--&lt;random&gt;</code> format you mentioned:</p>\n<p><strong>1. Update your <code>schema.prisma</code>:</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>model User {\n  // Use a standard default to satisfy TS, but override it with the custom decorator\n\n  /// @defaultJs(generateUserId)\n  myId String @id @default(&quot;&quot;)\n  name String\n  email String @unique\n}\n</code></pre>\n<p><strong>2. Setup your Prisma Client:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>import { PrismaClient } from '@prisma/client';\nimport { withJsDefaults } from 'prisma-js-defaults';\nimport { jsDefaultsConfig } from './prisma/generated/js-defaults';\n\nconst prisma = new PrismaClient().$extends(\n    withJsDefaults(jsDefaultsConfig, {\n        generateUserId: () =&gt; `user--${Math.random().toString(36).substring(2, 10)}`\n    })\n);\n</code></pre>\n<p>You can find the setup instructions and source code here:</p>\n<ul>\n<li><strong>NPM:</strong> <a href=\"https://www.npmjs.com/package/prisma-js-defaults\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/prisma-js-defaults</a></li>\n<li><strong>GitHub:</strong> <a href=\"https://github.com/HokaigoTwin/prisma-js-defaults\" rel=\"nofollow noreferrer\">https://github.com/HokaigoTwin/prisma-js-defaults</a></li>\n</ul>\n<blockquote>\n<p><strong>Disclaimer:</strong> I am the author of this package. I built it because I was facing the exact same limitations described in this thread and couldn't find a clean workaround. If anyone tries it out, I would genuinely appreciate your feedback on whether it fully covers your use cases!</p>\n</blockquote>\n",
      "owner": {
        "link": "https://stackoverflow.com/users/32779361/hokai-twin",
        "user_id": 32779361,
        "user_type": "registered",
        "account_id": 46433510,
        "reputation": 1,
        "display_name": "Hokai Twin",
        "profile_image": "https://i.sstatic.net/rUoTHZ9k.jpg?s=256"
      },
      "score": -1,
      "answer_id": 79948010,
      "is_accepted": false,
      "question_id": 61585219,
      "creation_date": 1779988965,
      "last_edit_date": 1779993985,
      "content_license": "CC BY-SA 4.0",
      "last_activity_date": 1779993985
    }
  ],
  "tags_raw": [
    "javascript",
    "graphql",
    "graphql-js",
    "prisma",
    "prisma-graphql"
  ],
  "stats_raw": {
    "score": 5,
    "view_count": 1122,
    "is_answered": false,
    "answer_count": 1,
    "creation_date": 1588566679,
    "last_edit_date": null,
    "accepted_answer_id": null,
    "last_activity_date": 1779993985
  },
  "selection_meta": {
    "site": "stackoverflow",
    "api_wrapper": {
      "backoff": null,
      "has_more": true,
      "page_size": 8,
      "quota_max": 300,
      "quota_remaining": 294
    },
    "answer_fetch": {
      "backoff": null,
      "has_more": false,
      "answers_fetched": 1,
      "quota_remaining": 262,
      "answer_page_size": 3
    },
    "snapshot_version": "stackoverflow_question_v1",
    "selection_strategy": "tag_whitelist_unanswered_high_score_recent_active"
  },
  "created_at": "2026-05-28T22:02:15.815Z",
  "updated_at": "2026-05-28T22:02:15.815Z"
}