DEV Community

Cover image for Use Atlas Search (MongoDB) in a Next.js app using Prisma ORM
Omar Saúl Morales Ibarra
Omar Saúl Morales Ibarra

Posted on

1 1

Use Atlas Search (MongoDB) in a Next.js app using Prisma ORM

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 🧑‍💻

Code snippet

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
}
view raw gistfile1.txt hosted with ❤ by GitHub

And documentation of raw queries with Prisma.

Top comments (0)