Next.js Discord

Discord Forum

Fetching data from MongoDB

Answered
Kanni posted this in #help-forum
Open in Discord
KanniOP
Hello. Im trying to fetch data from my MongoDB database. I crated page: /app/crates/[id]/page.js:

import { connectToDB } from '../../../lib/mongodb'; export async function loader({ params }) { const db = await connectToDB(); const crate = await db.collection('crates').findOne({ id: params.id }); if (!crate) { throw new Response('Not Found', { status: 404 }); } console.log("Fetched crate data:", crate); return { crate }; } export default function CratePage({ data }) { console.log("Received data in component:", data); if (!data || !data.crate) { return <div>Loading...</div>; } const { crate } = data; return ( <div> <h1>{crate.name}</h1> </div> ); }

But when I reach that url, it logs: Received data in component: undefined


my /lib/mongodb.js:
import { MongoClient } from 'mongodb';

const uri = process.env.NEXT_PUBLIC_MONGODB_URI;
const dbName = process.env.NEXT_PUBLIC_MONGODB_DB;

let cachedDb = null;

async function connectToDB() {
if (cachedDb) {
return cachedDb;
}

const client = await MongoClient.connect(uri);

const db = client.db(dbName);
cachedDb = db;
return db;
}

export { connectToDB };
Answered by Ray
there is no loader function in next, you need to execute it yourself
View full answer

5 Replies

are you in the correct server? this code is for remix lol
if its remix, use const data = useLoaderData()
KanniOP
Thank you for your response @Ray . To clarify, I am working with Next.js, not Remix. My project is using the latest Next.js version with the new /app directory structure for file-based routing. I am facing an issue where the loader function in my /app/crates/[id]/page.js file is not passing the fetched data from MongoDB to the component correctly. The data logs as undefined in the component. Any insights or suggestions specific to Next.js would be greatly appreciated.
@Kanni Thank you for your response <@743561772069421169> . To clarify, I am working with Next.js, not Remix. My project is using the latest Next.js version with the new /app directory structure for file-based routing. I am facing an issue where the loader function in my /app/crates/[id]/page.js file is not passing the fetched data from MongoDB to the component correctly. The data logs as undefined in the component. Any insights or suggestions specific to Next.js would be greatly appreciated.
import { notFound } from "next/navigation";

export async function getCrate(id:string) {
    const db = await connectToDB();
    return db.collection('crates').findOne({ id });
}

export default function CratePage({ params }: { params: { id: string }}) {
   const crate = getCrate(params.id)

    if (!crate) {
        notFound()
    }

    return (
        <div>
            <h1>{crate.name}</h1>
        </div>
    );
}
Answer