Enforcing foreign key constraints during the creation of a Prisma model

I've implemented a createUser function in my user.server.ts file:

export async function createUser(username: User["username"], email: User["email"], password: string) {
  const hashedPassword = await bcrypt.hash(password, 10)

  const user = await prisma.user.create({
    data: {
      email,
      username,
      role: {
        create: {
          name: ValidRoles["User"]
        }
      },
      hashed_password: hashedPassword,
    },
  })

  return prisma.userProfile.create({
    data: {
       user: {
        connect: user
       },
       userId: user.id,
    }
  })
}

This aligns with the following Schema:

model User {
  id       Int    @id @default(autoincrement())
  username String @unique @default("user")
  email    String    @unique
  hashed_password String
  role     Role      @relation(fields: [roleId], references: [id]) // Fields: PK, references: FK
  roleId   Int       @default(0)
  
  profile UserProfile @relation(fields: [profileId], references: [id], onUpdate: Cascade)
  profileId Int @unique @default(1)
  
  createdAt DateTime @default(now())
  updatedAt DateTime @default(now()) @updatedAt
}

model UserProfile {
  id Int @id @default(autoincrement())
  user User?
  userId Int @unique
}

However, when attempting to register a new user, I encounter the following error:

Error: 
Invalid `prisma.user.create()` invocation in
app\models\user.server.ts:18:34

  15 export async function createUser(username: User["username"], email: User["email"], password: string) {
  16 const hashedPassword = await bcrypt.hash(password, 10)
  17 
  
→ 18 const user = await prisma.user.create(
Foreign key constraint failed on the field: `User_profileId_fkey (index)`
at Zr.handleRequestError (node_modules\@prisma\client\runtime\library.js:171:6414)
at Zr.handleAndLogRequestError (node_modules\@prisma\client\runtime\library.js:171:5948)
at Zr.request (node_modules\@prisma\client\runtime\library.js:171:5786)
at t._request (node_modules\@prisma\client\runtime\library.js:174:10455)
at createUser (app\models\user.server.ts:18:16)
at action (app\routes\register.tsx:26:9)
at Object.callRouteActionRR (build\server.js:39464:20)
at callLoaderOrAction (build\server.js:38586:18)
at submit (build\server.js:38277:20)
at queryImpl (build\server.js:38240:27)

I believed my relations were correct, but if they are not, could someone provide clarification? If not, what is the issue and how can it be resolved? Any assistance would be greatly appreciated.

Answer №1

userProfile UserProfile @relation(fields: [profileId], references: [id], onUpdate: Cascade)
userId Int @unique @default(1)

It seems that the userId is set to NOT NULL with a default value of 1. If there is no UserProfile record with an id of 1, this could cause issues in the database.

To avoid this, you may want to consider making the reference nullable like so:

userId Int? @unique

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the generalization of class member initialization in TypeScript

I am looking to make some modifications to the Blog constructor provided in the "Minimal working example" linked below. The objective is to refactor it using pseudo-code by leveraging a generic ModelHelper class to initialize the members of the "Blog" clas ...

The type '(dispatch: Dispatch<any>, ownProps: OwnProps) => DispatchProps' does not match the parameter type 'DispatchProps'

Currently, I am working on a React application using Redux and TypeScript. I came across this insightful article that provided guidance on creating types for the mapStateToProps and mapDispatchToProps functions. Below is the code for my container: import ...

The Unusual Behavior of Typescript Partial Interfaces

While reviewing the code in a repository I am currently working on, I stumbled upon something that seemed completely incorrect. Here is a snippet of what caught my attention. interface Car { make: string model: string } type SomeType = Partial<Car& ...

Tips for setting up the configuration of @typescript-eslint guidelines

I am in the process of transitioning to @typescript-eslint but I am finding the documentation to be quite inadequate. One specific issue I am facing is the errors like the following: Line 58: Expected a semicolon @typescript-eslint/member-del ...

Using Angular to Bind Checkbox Value in Typescript

I have a challenge of creating a quiz where a card is displayed with 4 questions structured like this: <div class="col-md-6"> <div class="option" id="Answer1"> <label class="Answer1"> <input value= "Answer1" type="checkbox ...

Creating a dual-element display in React within a single frame

My code looks like this: <Box> <SomeIcon/> <HightlightSearch query={query}> {text} </HightlightSearch> </Box> The HighlightSearch function uses innerHTML to highlight query results in the child (text). It's a simpl ...

Completing a Promise Chain with the Power of Node, MySQL, and TypeScript

I'm currently utilizing node and typescript. In my setup, there's a controller and a repository. Strangely, I am able to log data everywhere except right after the return from the repository. As a result, the controller doesn't receive any d ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

I'm struggling to find a solution to this pesky TypeScript error that keeps popping up in the button component's styling. How can

An error related to style is appearing: <Button style = No overload matches this call. Overload 1 of 3, '(props: { href : string; } & { children?: React Node; classes?: Partial<Button Classes> | undefined; color?: "primary" | ...

Exploring Vue.js lifecycle events and when to begin loading store properties (Vue.observable)

Currently, I am utilizing Vue.observable() for state management and it is crucial for two store properties to be fully loaded before most views are rendered by vue-router. I have attempted implementing the loading logic in various lifecycle events such as ...

Why do callbacks in Typescript fail to compile when their arguments don't match?

In my current project, I encountered a scenario where a React callback led to a contrived example. interface A { a: string b: string } interface B { a: string b: string c: string } function foo(fn: (a: A) => void, a: A) { fn( ...

How to extract multiple literals from a string using Typescript

type Extracted<T> = T extends `${string}${'*('}${infer A}${')+'}${string}${'*('}${infer A}${')+'}${string}` ? A : never type Result1 = Extracted<'g*(a12)+gggggg*(h23)+'> // 'a12' | &a ...

Guide on subscribing to an object from a service in Angular 2/5

I am facing an issue where I need to update my property component with data received from the server. In the Service, I have implemented something like this: private events: Event[] = []; eventChanged = new Subject<any>(); // Edit: added an observa ...

The NgModule recognition system does not detect my library module

My AccordionModule within my Angular 2 library initially encountered a problem of not being recognized as an NgModule during the first compilation by angular-cli. However, it automatically reloaded after the error and was then successfully compiled with th ...

Is it possible to remove a single index after adding multiple new indexes?

I am currently using a PostgreSQL database that contains a table named film_ratings. CREATE TABLE film_ratings ( id serial NOT NULL, film_id integer NOT NULL, user_id integer NOT NULL, rating smallint NOT NULL, inserted_datetime timestamp withou ...

Use Advanced Encryption Standard Algorithm (AES) to encrypt text with TypeScript and decrypt it using C# for enhanced security measures

Struggling with implementing encryption in TypeScript and decryption in C#. After searching online, I found some resources related to JavaScript, not TypeScript. Encrypt in JavaScript and decrypt in C# with AES algorithm Encrypt text using CryptoJS libra ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Generate and insert a set of 10 random rows for every unique identifier in MSSQL

I am faced with a task involving a MSSQL table holding IDs, referred to as TBL1. Additionally, there is another table containing around 1 million data entries, known as TBL2 My goal is to randomly select and insert 10 rows from TBL2 into a new table name ...

The command "tsc" was not found in this bash session

Currently, I am using a MAC and attempting to set up TypeScript. I followed the installation process by running sudo npm install -g typescript and received the following output: Password: /Users/<myuserid>/node/bin/tsc -> /Users/<myuserid& ...