Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure.
The error message received is:
TypeError: Cannot read properties of undefined (reading 'id')
at GET (webpack-internal:///(sc_server)/./app/api/shop/[id]/route.tsx:14:30)
// Additional lines of error messages...
Below is the code being used:
/app/api/shop/[id]/route.tsx
import { connectToDatabase } from "@/lib/mongo";
import { NextRequest, NextResponse } from "next/server";
import { ObjectId } from "mongodb";
export async function GET(req: NextRequest, res: NextResponse) {
try {
const id = req.query.id;
const client = await connectToDatabase();
const db = client.db("MyShopDB");
const oneProduct = await db.collection("Products").findOne({ _id: ObjectId(id) });
if(oneProduct)
return NextResponse.json(oneProduct)
else
return res.status(404).json({message: "Products Not Found"})
} catch (error) {
console.log(error);
return new Response("Failed to fetch all prompts", { status: 500 })
}
}
For fetching all products, you can refer to the following code:
/app/api/shop/route.tsx
import { connectToDatabase } from "@/lib/mongo";
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest, res: NextResponse) {
try {
const client = await connectToDatabase();
const db = client.db("MyShopDB");
const allProducts = await db.collection("Products").find().toArray();
return NextResponse.json(allProducts);
} catch (error) {
return new Response("Failed to fetch all prompts", { status: 500 })
}
}