Testing how to use MongoDB in Next.js using Prisma I was having some issues when trying to use Atlas Search. Here a code snippet on how I solved my issue. Hope is useful for someone 😀 Happy coding 🧑💻
Here the Github gist if you need to copy the code 😉
// app/api/products/search/route.ts | |
import { NextRequest, NextResponse } from "next/server"; | |
import prisma from "@/lib/connect"; | |
export async function GET(req: NextRequest) { | |
try { | |
// Extract search query from the URL | |
const q = req.nextUrl.searchParams.get("q"); | |
if (!q || q.trim() === "") { | |
return NextResponse.json( | |
{ error: "Query parameter 'q' is required" }, | |
{ status: 400 } | |
); | |
} | |
// Run search query on products collection | |
const products = await prisma.$runCommandRaw({ | |
aggregate: "Product", | |
pipeline: [ | |
{ | |
$search: { | |
index: "searchProducts", | |
text: { | |
query: q, | |
path: { | |
wildcard: "*", // Search across all fields | |
}, | |
}, | |
}, | |
}, | |
], | |
cursor: {}, | |
}); | |
console.log("GET searched products", products); | |
// Return the search result | |
return NextResponse.json(products); | |
} catch (error) { | |
console.error("Error getting products", error); | |
return NextResponse.json( | |
{ error: "Error retrieving products", details: error.message }, | |
{ status: 500 } | |
); | |
} | |
} | |
// prisma/schema.prisma | |
// this is the prisma schema file | |
generator client { | |
provider = "prisma-client-js" | |
} | |
datasource db { | |
provider = "mongodb" | |
url = env("DATABASE_URL") | |
} | |
model Product { | |
id String @id @default(cuid()) @map("_id") | |
name String | |
key String @unique | |
description String? | |
iva Float? | |
ieps Float? | |
isr Float? | |
sku String | |
price Float | |
createdAt DateTime @default(now()) | |
updatedAt DateTime @updatedAt | |
} |
Top comments (0)