Prisma findMany where clause behavior with undefined values #21384
Unanswered
MortezaIsvand
asked this question in
Q&A
Replies: 2 comments 1 reply
-
Hello @MortezaIsvand 👋 Did you had a look at this section of docs: Undefined and Null The behavior you're experiencing is due to how Prisma handles Can you do something like this and check if you get the correct behaviour? import prisma from "@/prisma/client";
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const search = searchParams.get("search") || "";
let whereClause = {};
if (search) {
whereClause = {
title: {
contains: search,
mode: "insensitive",
},
};
}
try {
const posts = await prisma.post.findMany({
where: whereClause,
select: {
id: true,
title: true,
content: true,
tag: true,
},
});
return NextResponse.json(posts, { status: 200 });
} catch (error) {
return NextResponse.json(
{ message: "Could not fetch posts" },
{ status: 500 }
);
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
-
According to the Prisma docs, if |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Question
Hello everyone,
I’m currently working on a project where I’m using Prisma to interact with my database. I have a situation where I want to fetch posts based on a search term. Here’s the code snippet:
In the
where
clause of the findMany function, I want to include thewhere
condition only when thesearch
parameter is notundefined
. Whensearch
is undefined I want thewhere
clause to have no effect at all.The above code doesn't work as expected. As a matter of fact, when the
search
is undefined nothing will be rendered in the home page, but when it is a string or an empty string all posts will be fetched.How to reproduce (optional)
Expected behavior (optional)
No response
Information about Prisma Schema, Client Queries and Environment (optional)
// Add your schema.prisma
// Add any relevant Prisma Client queries here
OS:
Database:
Node.js version:
Run
prisma -v
to see your Prisma version and paste itBeta Was this translation helpful? Give feedback.
All reactions