Bird
0
0

Given the following Prisma models:

medium📝 Predict Output Q4 of 15
NestJS - Database with Prisma
Given the following Prisma models:

model User {
  id    Int     @id @default(autoincrement())
  name  String
  posts Post[]
}

model Post {
  id      Int    @id @default(autoincrement())
  title   String
  userId  Int
  user    User   @relation(fields: [userId], references: [id])
}

What will prisma.user.findUnique({ where: { id: 1 }, include: { posts: true } }) return if the user with id = 1 has no posts?
ANull because the user has no posts
BAn object with the user data and posts as null
CAn error because posts cannot be empty
DAn object with the user data and an empty array for posts
Step-by-Step Solution
Solution:
  1. Step 1: Understand the relation

    The User model has a one-to-many relation to Post via the posts field.
  2. Step 2: Query behavior

    When including related records with include: { posts: true }, Prisma returns an array of posts. If no posts exist, it returns an empty array, not null.
  3. Final Answer:

    An object with the user data and an empty array for posts -> Option D
  4. Quick Check:

    Check if posts is an array even when empty [OK]
Quick Trick: Empty relations return empty arrays, not null [OK]
Common Mistakes:
  • Assuming posts will be null if no related records exist
  • Expecting an error when no posts are found
  • Thinking the entire user object will be null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes