I'm developing a NestJS application using Prisma. I wrote a service that take a CreateHotelDTO to find a hotel and create one if the hotel didn't exist with upsert. After many tries to modify schema and query, I still couldn't make it to work successfully (got the error in the title). What have I done wrong?
My schema:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Hotel{
id Int @id @default(autoincrement())
hotelCode String @unique
rooms Room[]
}
model Room{
id Int @id @default(autoincrement())
roomName String @unique
status RoomStatus @default(BOOKED)
hotel Hotel @relation(fields: [hotelCode], references: [hotelCode])
hotelCode String @unique
}
enum RoomStatus {
BOOKED
CHECKIN
CHECKOUT
}
My service.ts:
import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/orm/prisma.service';
import { CreateHotelDTO } from './dtos/create-hotel.dto';
@Injectable()
export class HotelsService {
constructor(private prisma: PrismaService) {}
async createHotel(createHotelDTO: CreateHotelDTO): Promise<any> {
const hotel = await this.prisma.hotel.upsert({
where: { hotelCode: createHotelDTO.hotelCode },
update: {},
create: {
hotelCode: createHotelDTO.hotelCode,
rooms: {
createMany: {
data: createHotelDTO.rooms,
},
},
},
});
return hotel;
}
}
My request body using postman:
{
"hotelCode": "CITY",
"rooms": [
{
"roomName":"201",
"status": "BOOKED"
},
{
"roomName":"202",
"status": "BOOKED"
},
{
"roomName":"203",
"status": "BOOKED"
}
]
}
The full error log:
Invalid `this.prisma.hotel.upsert()` invocation in
src\features\hotels\hotels.service.ts:10:43
7 constructor(private prisma: PrismaService) {}
8
9 async createHotel(createHotelDTO: CreateHotelDTO): Promise<any> {
→ 10 const hotel = await this.prisma.hotel.upsert(
Unique constraint failed on the constraint: `Room_hotelCode_key`
PrismaClientKnownRequestError:
Invalid `this.prisma.hotel.upsert()` invocation in
src\features\hotels\hotels.service.ts:10:43
7 constructor(private prisma: PrismaService) {}
8
9 async createHotel(createHotelDTO: CreateHotelDTO): Promise<any> {
→ 10 const hotel = await this.prisma.hotel.upsert(
Unique constraint failed on the constraint: `Room_hotelCode_key`
...
So the problem was I messed up with prisma db push
and prisma migrate dev
. Here's what happened:
prisma migrate dev
.prisma db push
. Nothing changed inside of the database. This is where the problem arised.The solution is removing all the migrate history and run prisma db push
again. Everything works perfectly