Upsert: Help in finalizing the command, gettings two errors - prisma

My models:
model Show {
id Int #id #default(autoincrement())
tvmazeId Int
name String
type Type #relation(fields: [typeId], references: id)
typeId Int
language Language #relation(fields: [languageId], references: id)
languageId Int
genres GenresOnShows[]
status Status #relation(fields: [statusId], references: id)
statusId Int
runtime Int?
premiered DateTime?
ended DateTime?
network Network? #relation(fields: [networkId], references: id)
country Country? #relation(fields: [countryId], references: id)
countryId Int
networkId Int
webchannel Webchannel? #relation(fields: [webchannelId], references: id)
webchannelId Int
tvrageId String? #unique
thetvdbId String? #unique
imdbId String? #unique
imageMed String? #unique
imageOrig String? #unique
summary String
}
model Status {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Type {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Language {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Country {
id Int #id #default(autoincrement())
name String #unique
code String #unique
timezone String
shows Show[]
}
model Network {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Webchannel {
id Int #id #default(autoincrement())
name String #unique
shows Show[]
}
model Genre {
id Int #id #default(autoincrement())
name String #unique
shows GenresOnShows[]
}
model GenresOnShows {
show Show #relation(fields: [showId], references: [id])
showId Int
genre Genre #relation(fields: [genreId], references: [id])
genreId Int
##id([showId, genreId])
}
What i try is getting show information from an api and populate the database. The problem is, that i need to populate related tables (like network, country, etc.) in the same action.
Here is how i get for example the country:
const country = await prisma.country.upsert(
{
where: {
name: show["network"]["country"]["name"]
},
update: {},
create: {
name: show["network"]["country"]["name"],
code: show["network"]["country"]["code"],
timezone: show["network"]["country"]["timezone"],
}
}
)
and heres the statement i use to try to update the show:
const showInDb = await prisma.show.upsert(
{
where: {
tvmazeId: show["id"]
},
update: {
typeId: {connect: {type}},
languageId: {connect: {language}},
genreConnectOrCreate: genreConnectOrCreate,
statusId: {connect: {status}},
networkId: {connect: {network}},
countryId: {connect: {country}},
webchannelId: {connect: {webchannel}},
name: show["name"],
runtime: parseInt(show["runtime"]),
premiered: new Date(show["premiered"]),
ended: new Date(show["ended"]),
tvrageId: show["externals"]["tvrage"].toString(),
tvdbId: show["externals"]["thetvdb"],
imdbId: show["externals"]["imdb"],
tvmazeId: show["id"],
imageMed: show["image"]["medium"],
imageOrig: show["image"]["original"],
summary: show["summary"]
},
create: {
typeId: {connect: {type}},
languageId: {connect: {language}},
genreConnectOrCreate: genreConnectOrCreate,
statusId: {connect: {status}},
networkId: {connect: {network}},
countryId: {connect: {country}},
webchannelId: webchannel,
name: show["name"],
runtime: parseInt(show["runtime"]),
premiered: new Date(show["premiered"]),
ended: new Date(show["ended"]),
tvmazeId: show["id"],
tvrageId: show["externals"]["tvrage"].toString(),
tvdbId: show["externals"]["thetvdb"],
imdbId: show["externals"]["imdb"],
imageMed: show["image"]["medium"],
imageOrig: show["image"]["original"],
summary: show["summary"]
}
}
)
I tried with the ID (for example countryId aswell as country itself). The error i get when using countryId is:
Unknown arg countryId in update.countryId for type ShowUpdateInput. Did you mean country?
if i use country:
Unknown arg country in update.country.connect.country for type CountryWhereUniqueInput. Did you mean code?
I also tried to privde the country without the connect like so:
country: country,
what is the correct way to do that?

Related

name: 'LinkAccountError', [next-auth][error][adapter_error_linkAccount]

I am making a sign up page with 3 providers (Twitter, Facebook and Instagram) using next-auth and prisma with mongoDB. The issue appears when I try to sign up with any of the providers. I think the prisma schema is the problem. Here is the error that I receive:
Invalid `p.account.create()` invocation in
C:\...\node_modules\#next-auth\prisma-adapter\dist\index.js:19:42
16 },
17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }),
18 deleteUser: (id) => p.user.delete({ where: { id } }),
→ 19 linkAccount: (data) => p.account.create({
data: {
provider: 'instagram',
type: 'oauth',
providerAccountId: '62921xxxxxx98535',
access_token: 'IGQVJYdU...',
user_id: 178xxxx,
~~~~~~~
userId: '63e2538xxxx'
}
})
Unknown arg `user_id` in data.user_id for type AccountUncheckedCreateInput. Did you mean `userId`? Available args:
type AccountUncheckedCreateInput {
id?: String
userId: String
type: String
provider: String
providerAccountId: String
}
I have red all the documentations about, chatGPT also didn't help much. The prisma schema looks like this:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String #id #default(auto()) #map("_id") #db.ObjectId
name String?
email String? #unique
emailVerified DateTime? #map("email_verified")
image String?
accounts Account[]
sessions Session[]
##map("users")
}
model Account {
id String #id #default(auto()) #map("_id") #db.ObjectId
userId String #db.ObjectId
type String
provider String
providerAccountId String #map("provider_account_id")
refresh_token String? #db.String
access_token String? #db.String
expires_at Int?
token_type String?
scope String?
id_token String? #db.String
session_state String?
user User #relation(fields: [userId], references: [id], onDelete: Cascade)
##unique([provider, providerAccountId])
##map("accounts")
}
model Session {
id String #id #default(auto()) #map("_id") #db.ObjectId
sessionToken String #unique #map("session_token")
userId String #db.ObjectId
expires DateTime
user User #relation(fields: [userId], references: [id], onDelete: Cascade)
##map("sessions")
}
model VerificationToken {
identifier String #id #default(auto()) #map("_id") #db.ObjectId
token String #unique
expires DateTime
##unique([identifier, token])
##map("verificationtokens")
}
You are passing user_id parameter while creating an account, but there is no field named user_id in the Account model in your schema file.
If you need to pass user_id while creating an account then you need to define it in the Account model as well.

Unique constraint failed on the constraint: `Bug_authorId_key`

I am trying to implement a relation querie with Prisma ORM but this error does not allow.
My system consists in a bugtracker, where the user can report bugs. So I'm linking the User with the bugs. When I try to create a new data this error appears: "Unique constraint failed on the constraint: Bug_authorId_key"
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model User {
id Int #id #default(autoincrement())
name String
email String #unique
password String
role String #default("User")
bugs Bug[]
teamId Int?
team Team? #relation(fields: [teamId], references: [id])
}
model Team {
id Int #id #default(autoincrement())
name String
users User[]
admins Admin[]
}
model Admin {
id Int #id #default(autoincrement())
name String
email String #unique
password String
role String #default("Admin")
teamId Int?
team Team? #relation(fields: [teamId], references: [id])
}
model Bug {
id Int #id #default(autoincrement())
title String
description String
status String
authorId Int
author User #relation(fields: [authorId], references: [id])
}
const bug = await prisma.bug.create({
data: {
title: req.body.title,
status: req.body.status,
description: req.body.description,
author: {
connect: {id: req.body.authorId}
}
}
})

prisma nested writes throw unknown args

I have the shorten schema like that:
model PATIENT {
patient_id Int #id #default(autoincrement())
patient_name String
patient_identity_card BigInt #unique
password String
wallet_id Int?
birthday DateTime
address String
status_id Int
gender String #default("Nam")
phone String #default("0935438280")
current_treatment_place_id Int
avatar_url String?
treatment_place TREATMENT_PLACE #relation(fields: [current_treatment_place_id], references: [place_id])
status PATIENT_STATUS #relation(fields: [status_id], references: [status_id])
card CART?
patient_passive_contact PATIENT_CONTACT[] #relation("ActiveContact_referredToPatient")
patient_active_contact PATIENT_CONTACT[] #relation("PassiveContact_referredToPatient")
BE_MANAGED_HISTORY BE_MANAGED_HISTORY[]
}
model BE_MANAGED_HISTORY {
place_id Int
patient_id Int
time DateTime
status_id Int
status PATIENT_STATUS #relation(fields: [status_id], references: [status_id])
patient PATIENT #relation(fields: [patient_id], references: [patient_id])
place TREATMENT_PLACE #relation(fields: [place_id], references: [place_id])
change_type_id Int
change_type CHANGE_MANAGED_HISTORY_TYPE #relation(fields: [change_type_id], references: [type_id])
##id([place_id, patient_id, time])
}
I want to create a BE_MANAGED_HISTORY record and through it create a PATIENT record with needed information. The nested writes below:
const res = await prisma.BE_MANAGED_HISTORY.create({
data: {
place_id: treatmentPlaceId,
time: new Date(startDate),
status_id: patientStatus,
change_type_id: 1,
patient: {
create: {
patient_name: patientName,
gender,
birthday: new Date(birthday),
patient_identity_card: identity,
password: hashedPassword,
phone,
address,
status_id: patientStatus,
current_treatment_place_id: treatmentPlaceId,
avatar_url: avatarUrl,
}
}
},
})
But prisma throws an error:
Unknown arg patient in data.patient for type BE_MANAGED_HISTORYUncheckedCreateInput. Did you mean patient_id?
Argument patient_id for data.patient_id is missing.
So can I create an beManagedHistory and create an patient inside nested writes?
We have to create a PATIENT record first, and nested in it creating a BE_MANAGED_HISTORY record.

how to make one to many relation with foreign key

model Categories{
id Int #default(autoincrement()) #id
name String #db.VarChar(30)
products Products[]
}
model Products{
id Int #default(autoincrement()) #id
englishName String #db.VarChar(40) #map("english_name")
category Categories #relation(fields: [categoryId], references: [id])
categoryId String
imgUrl String #map("img_url")
}
Hi! I'm connecting model categories and model products as one to many relations. I want to set categoryId in model Products as a foreign key, but it's not working. Someone please help me! Thank you!
I have modified a little bit your schema:
model Categories{
id Int #default(autoincrement()) #id
name String
products Products[] #relation()
}
model Products{
id Int #default(autoincrement()) #id
englishName String
category Categories #relation(fields: [categoryId], references: [id])
categoryId Int
}
After I have run the migration and finally I have executed the following:
const { PrismaClient } = require('#prisma/client');
const prisma = new PrismaClient();
const saveData = async () => {
const category = await prisma.categories
.create({
data: {
name: 'Category 1',
}
});
console.log(category);
const product = await prisma.products
.create({
data: {
englishName: 'Product 1',
category: {
connect: {
id: category.id
},
}
}
});
console.log(product);
const products = await prisma.products
.findMany({
include: {
category: true
}
});
console.log(products);
};
saveData();
and here you go the result

prisma2 how to relate one-to-many and many-to-one?

I need some help to understqnd how to set my data modelisation.
What i'm trying to do is :
Reference a group ID in User model. A user can only be in one group, this is what i've done below.
Reference in Group Model all users that are inside a group. This is what I need help with.
model User {
id String #id #default(uuid())
email String #unique
role Role #default(USER)
group Group? #relation(fields: [group_id], references: [id], onDelete: SetNull)
group_id String
created_at DateTime #default(now())
updated_at DateTime #updatedAt
##map("user")
}
model Group {
id String #id #default(uuid())
name String
users User[]
created_at DateTime #default(now())
updated_at DateTime #updatedAt
deleted Boolean #default(false)
##map("group")
}
How can I make this list of User when I already have users User[] for the relation in User model ?
(BTW i've read the doc but i'm totally lost...)
I think your code is correct, you can use prisma-client to test
This is an example of this relation
model Agents {
id Int #id #default(autoincrement()) #db.UnsignedInt
name String? #db.VarChar(255)
owner String? #db.VarChar(255)
address String? #db.Text
lat String? #db.VarChar(10)
lng String? #db.VarChar(10)
tel String? #db.VarChar(13)
mobile String? #db.VarChar(11)
workTime String? #db.VarChar(255)
province Provinces #relation(fields: [provinceId], references: [id])
provinceId Int #db.UnsignedInt
createDateTime DateTime #default(now()) #db.Timestamp(0)
updateDateTime DateTime? #db.Timestamp(0)
##index([provinceId], name: "provinceId")
##map(name: "agents")
}
model Provinces {
id Int #id #default(autoincrement()) #db.UnsignedInt
name String? #db.VarChar(255)
coords String? #db.Text
createDateTime DateTime #default(now()) #db.Timestamp(0)
updateDateTime DateTime? #db.Timestamp(0)
agents Agents[]
##map(name: "provinces")
}