VLDR
VLDR

Reputation: 53

Prisma Error: "Operation 'createOne' for model 'X' does not match any query"

I'm encountering a perplexing issue with Prisma in my Next.js application and need some help to resolve it. I'm using Prisma to interact with a MySQL database, and I'm trying to create a record in the 'Quiz' model, but I keep getting the error message:

Operation 'createOne' for model 'Quiz' does not match any query.

Code:

I have a POST method in my API for creating a quiz. Below is the code:


export const POST = async (req: Request, res: Response) => {
  try {
    // ... (authentication and data parsing logic)

    // Attempt to create a new 'Quiz' record
    const quiz = await prisma.quiz.create({
      data: {
        userId: session.user.id,
        timeStarted: new Date(),
        topic,
      },
    });

    // ... (additional logic to create related records)

    return NextResponse.json({ quizId: quiz.id });
  } catch (error) {
    if (error instanceof ZodError) {
      return NextResponse.json({ error: error.issues }, { status: 400 });
    } else {
      // For logs purpose
      console.log('api/questions error: ', error);
      return NextResponse.json(
        { error: 'Something went wrong' },
        { status: 500 }
      );
    }
  }
};

Prisma Schema:

Here's my Prisma schema for the 'Quiz' and 'Question' models:

model Quiz {
  id          String     @id @default(cuid())
  userId      String
  timeStarted DateTime
  topic       String
  timeEnded   DateTime?
  user        User       @relation(fields: [userId], references: [id], onDelete: Cascade)
  questions   Question[]

  @@index([userId], name: "userId")
}

model Question {
  id         String   @id @default(cuid())
  question   String
  answer     String
  quizId     String
  options    Json
  isCorrect  Boolean?
  userAnswer String?
  quiz       Quiz     @relation(fields: [quizId], references: [id], onDelete: Cascade)

  @@index([quizId], name: "quizId")
}

And here is my Prisma Client to make sure only one PrismaClient is being initialized.

import { PrismaClient } from '@prisma/client';
import 'server-only';

declare global {
  // eslint-disable-next-line no-var, no-unused-vars
  var cachedPrisma: PrismaClient;
}

export let prisma: PrismaClient;
if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient();
} else {
  if (!global.cachedPrisma) {
    global.cachedPrisma = new PrismaClient({
      log: ['query', 'info', 'warn', 'error'],
      errorFormat: 'pretty',
    });
  }
  prisma = global.cachedPrisma;
}

What I've tried:

What I expected is the quiz should be created at the very least.

Upvotes: 0

Views: 1858

Answers (1)

R.Mike
R.Mike

Reputation: 46

I had the same error. So for me it worked after I did the following :

npx prisma generate 
npx prisma db push 

I had to close the server while doing that then :

npm run dev

Upvotes: 3

Related Questions