How do I create a required 1 to 1 relationship using Prisma?

Viewed 31

I want to create a user, with a predefined id and to transactionally create an authorization and profile connected to the user using nested writes. But the typescript compiler complains that I may only create nested objects, if I don't provide the predefined id. Or if I do provide one, I can't create the connected objects.

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

model User {
  id           String
  emailAddress String
  createdAt    DateTime @default(now())
  updatedAt    DateTime @default(now()) @updatedAt

  objectId String @id @default(auto()) @map("_id") @db.ObjectId

  profile UserProfile @relation(fields: [id], references: [userId])
  authentication UserAuthentication @relation(fields: [id], references: [userId])

  @@unique([id])
  @@unique([emailAddress])
  @@map("users")
}

model UserProfile {
  firstName    String
  lastName     String
  userId       String

  objectId String @id @default(auto()) @map("_id") @db.ObjectId

  user User?

  @@unique([userId])
  @@map("user-profiles")
}

model UserAuthentication {
  passwordHash String
  userId       String

  objectId String @id @default(auto()) @map("_id") @db.ObjectId

  user User?

  @@unique([userId])
  @@map("user-auths")
}

context.prisma.user
    .create({
      data: {
        id: userId,
        emailAddress: input.emailAddress.toLowerCase(),
        profile: {
          create: {
            userId,
            firstName: input.firstName,
            lastName: input.lastName
          }
        },
        authentication: {
          create: {
            userId,
            passwordHash
          }
        },
        createdAt,
        updatedAt: createdAt
      }
    })

The type compiler complains with an error saying that either the id or the authentication/profile are Type 'xxx' is not assignable to type 'never'.

How may I go and create all these objects using nested writes with a predefined id?

P.D.: Also apparently, I must repeat the userId on the create object, which I would think would be inferred. I don't know if this is correct.

I appreciate any knowledge you might share.

0 Answers
Related