Bird
Raised Fist0
NextJSframework~20 mins

CRUD operations with Prisma in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Prisma CRUD Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Prisma create operation in Next.js?

Consider this Next.js API route using Prisma to create a new user:

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const user = await prisma.user.create({
      data: { name: 'Alice', email: 'alice@example.com' }
    });
    res.json(user);
  } else {
    res.status(405).end();
  }
}

What will the response JSON contain after a successful POST request?

NextJS
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const user = await prisma.user.create({
      data: { name: 'Alice', email: 'alice@example.com' }
    });
    res.json(user);
  } else {
    res.status(405).end();
  }
}
A{"name": "Alice", "email": "alice@example.com"}
B{"error": "Method not allowed"}
C{"id": 1, "name": "Alice", "email": "alice@example.com"}
D{"message": "User created successfully"}
Attempts:
2 left
💡 Hint

Prisma returns the full created record including the auto-generated ID.

state_output
intermediate
2:00remaining
What is the result of this Prisma update operation?

Given this Prisma update code snippet in a Next.js API route:

const updatedUser = await prisma.user.update({
  where: { id: 5 },
  data: { email: 'newemail@example.com' }
});
console.log(updatedUser);

Assuming a user with id = 5 exists, what will console.log(updatedUser) output?

NextJS
const updatedUser = await prisma.user.update({
  where: { id: 5 },
  data: { email: 'newemail@example.com' }
});
console.log(updatedUser);
A{"id": 5, "name": "Existing Name", "email": "newemail@example.com"}
B{"id": 5, "email": "newemail@example.com"}
Cundefined
DThrows Prisma.PrismaClientKnownRequestError
Attempts:
2 left
💡 Hint

The update method returns the full updated record.

🔧 Debug
advanced
2:00remaining
Why does this Prisma delete operation cause an error?

Review this Next.js API route snippet:

export default async function handler(req, res) {
  if (req.method === 'DELETE') {
    const deletedUser = await prisma.user.delete({
      where: { email: 'nonexistent@example.com' }
    });
    res.json(deletedUser);
  } else {
    res.status(405).end();
  }
}

What error will this code throw if no user has the given email?

NextJS
const deletedUser = await prisma.user.delete({
  where: { email: 'nonexistent@example.com' }
});
ANo error, returns null
BTypeError: Cannot read property 'email' of undefined
CSyntaxError: Unexpected token delete
DPrisma.PrismaClientKnownRequestError: Record to delete does not exist.
Attempts:
2 left
💡 Hint

Deleting a non-existing record causes a specific Prisma error.

🧠 Conceptual
advanced
2:00remaining
Which Prisma query returns all users with emails ending in '.org'?

Choose the Prisma query that correctly fetches all users whose email ends with '.org'.

Aprisma.user.findMany({ where: { email: { endsWith: '.org' } } })
Bprisma.user.findMany({ where: { email: { contains: '.org' } } })
Cprisma.user.findMany({ where: { email: { startsWith: '.org' } } })
Dprisma.user.findMany({ where: { email: { equals: '.org' } } })
Attempts:
2 left
💡 Hint

Look for the operator that matches the end of a string.

📝 Syntax
expert
2:00remaining
What error does this Prisma upsert code produce?

Analyze this Prisma upsert code snippet:

await prisma.user.upsert({
  where: { id: 10 },
  update: { name: 'Bob' },
  create: { email: 'bob@example.com' }
});

What error will this code raise?

NextJS
await prisma.user.upsert({
  where: { id: 10 },
  update: { name: 'Bob' },
  create: { email: 'bob@example.com' }
});
ASyntaxError: Unexpected token 'await'
BPrisma.PrismaClientValidationError: Missing required field 'name' in create data.
CNo error, operation succeeds
DPrisma.PrismaClientKnownRequestError: Unique constraint failed on the fields: (`id`)
Attempts:
2 left
💡 Hint

Check if the create data includes all required fields.

Practice

(1/5)
1. What does the prisma.user.create() method do in Next.js with Prisma?
easy
A. It adds a new user record to the database.
B. It fetches all user records from the database.
C. It updates an existing user record.
D. It deletes a user record from the database.

Solution

  1. Step 1: Understand the method name

    The method create() is used to add new data in Prisma.
  2. Step 2: Match method to CRUD operation

    Creating means adding new records, so prisma.user.create() adds a new user.
  3. Final Answer:

    It adds a new user record to the database. -> Option A
  4. Quick Check:

    Create method = Add new record [OK]
Hint: Create method adds new data, not read or delete [OK]
Common Mistakes:
  • Confusing create() with findMany() which reads data
  • Thinking create() updates existing records
  • Assuming create() deletes records
2. Which of the following is the correct syntax to update a user with id 5 using Prisma in Next.js?
easy
A. prisma.user.edit({ where: { id: 5 }, data: { name: 'Alice' } })
B. prisma.user.modify({ id: 5, name: 'Alice' })
C. prisma.user.update({ where: { id: 5 }, data: { name: 'Alice' } })
D. prisma.user.change({ id: 5, data: { name: 'Alice' } })

Solution

  1. Step 1: Identify Prisma update syntax

    Prisma uses update() with where and data keys to update records.
  2. Step 2: Check option correctness

    Only prisma.user.update({ where: { id: 5 }, data: { name: 'Alice' } }) uses correct method update() and proper keys where and data.
  3. Final Answer:

    prisma.user.update({ where: { id: 5 }, data: { name: 'Alice' } }) -> Option C
  4. Quick Check:

    Update method uses where and data keys [OK]
Hint: Update uses update({ where, data }) syntax [OK]
Common Mistakes:
  • Using non-existent methods like modify(), change(), edit()
  • Missing where or data keys in update()
  • Passing id directly without where object
3. Given this code snippet in Next.js with Prisma:
const users = await prisma.user.findMany({ where: { active: true } });
console.log(users.length);

What will console.log(users.length) output?
medium
A. Always 0, because findMany returns undefined.
B. The total number of users, active or not.
C. An error because findMany needs data key.
D. The number of active users in the database.

Solution

  1. Step 1: Understand findMany with where filter

    The findMany() method returns an array of records matching the where condition.
  2. Step 2: Analyze the filter condition

    Only users with active: true are returned, so users.length is count of active users.
  3. Final Answer:

    The number of active users in the database. -> Option D
  4. Quick Check:

    findMany with where returns filtered array [OK]
Hint: findMany returns array; length counts filtered records [OK]
Common Mistakes:
  • Thinking findMany returns undefined or error
  • Ignoring the where filter effect
  • Assuming it returns all users without filter
4. Identify the error in this Prisma delete operation:
await prisma.user.delete({ id: 10 });
medium
A. Missing the 'where' key wrapping the id.
B. Using delete() instead of remove().
C. id should be a string, not a number.
D. delete() cannot be used with await.

Solution

  1. Step 1: Check delete() method syntax

    Prisma's delete() requires an object with a where key specifying the record to delete.
  2. Step 2: Identify missing where key

    The code passes { id: 10 } directly, missing where: { id: 10 }.
  3. Final Answer:

    Missing the 'where' key wrapping the id. -> Option A
  4. Quick Check:

    Delete needs where key with id [OK]
Hint: Delete needs where: { id } object, not just id [OK]
Common Mistakes:
  • Omitting where key in delete()
  • Using remove() which does not exist in Prisma
  • Thinking id type must be string always
  • Believing delete() can't be awaited
5. You want to update a user's email only if the user exists, otherwise create a new user with that email. Which Prisma method best fits this use case in Next.js?
hard
A. prisma.user.create({ data: { email } })
B. prisma.user.upsert({ where: { email }, update: { email }, create: { email } })
C. prisma.user.update({ where: { email }, data: { email } })
D. prisma.user.findUnique({ where: { email } })

Solution

  1. Step 1: Understand the upsert method

    Upsert updates if record exists, else creates new one in Prisma.
  2. Step 2: Match use case to method

    Since we want to update or create based on existence, upsert() fits perfectly.
  3. Final Answer:

    prisma.user.upsert({ where: { email }, update: { email }, create: { email } }) -> Option B
  4. Quick Check:

    Upsert = update or create [OK]
Hint: Use upsert to update or create in one call [OK]
Common Mistakes:
  • Using update() alone which fails if user missing
  • Using create() alone which fails if user exists
  • Using findUnique() which only reads data