Performance: Prisma ORM setup
This affects the initial server response time and database query efficiency in your Next.js app.
Jump into concepts and practice - no test required
import { PrismaClient } from '@prisma/client'; let prisma; if (!global.prisma) { global.prisma = new PrismaClient(); } prisma = global.prisma; export default async function handler(req, res) { const users = await prisma.user.findMany(); res.json(users); }
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); export default async function handler(req, res) { const users = await prisma.user.findMany(); res.json(users); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| New PrismaClient per request | N/A (server-side) | N/A | N/A | [X] Bad |
| Singleton PrismaClient instance | N/A (server-side) | N/A | N/A | [OK] Good |
schema.prisma file in a Next.js project using Prisma ORM?schema.prismaschema.prisma. Styling is done with CSS or styling libraries.schema.prisma = data models [OK]new keyword to create an instance: new PrismaClient().schema.prisma:
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(false)
}
What will be the result of this Prisma Client query?
const posts = await prisma.post.findMany({ where: { published: true } });
console.log(posts);published. The query filters posts where published is true.findMany returns an array of all matching posts, so it returns all posts with published: true.import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default async function handler(req, res) {
const user = await prisma.user.findUnique({ where: { id: req.query.id } });
res.json(user);
}
But you get an error: TypeError: Cannot read property 'id' of undefined. What is the likely cause?Cannot read property 'id' of undefined, meaning req.query is undefined or id is missing.?id=someValue so req.query.id exists.req.query object is undefined or missing id -> Option CComment related to Post in your Prisma schema, where each comment belongs to one post. Which of the following schema additions correctly sets up this relationship?postId and a relation field post with @relation specifying fields and references.comments field as an array of Comment to represent one-to-many relation.