skip to Main Content

i am a beginner and facing an issue with fetching data from MongoDB in Next.js. The client side is functioning properly and I have checked the console logs and schema validation. Additionally, I have used Zod validation

import { NextResponse } from "next/server";
import { MongoClient, MongoClientOptions } from "mongodb";
import { Request } from "express";
import express from "express";

const app = express();
app.use(express.json());

interface CustomMongoClientOptions extends MongoClientOptions {
 useUnifiedTopology?: boolean;
}

export async function POST(req: Request): Promise<NextResponse> {
 // Explicitly type req and return type
 if (req.method === "POST") {
   try {
     console.log("Received data:", req.body);
     const {
       first_name = "",
       last_name = "",
       email = "",
       job_title = "",
       company_name = "",
       website_name = "",
       help = "",
       services = "",
       info = "",
     } = req.body; // Access req.body directly without await
     console.log("firstname", first_name);

     const uri: string = process.env.MONGODB_URI || ""; // Use environment variable for URI

     const client = new MongoClient(uri, {
       useUnifiedTopology: true,
       useNewUrlParser: true,
     } as CustomMongoClientOptions);

     await client.connect();
     const collection = client.db("codeseo").collection("userdata");
     const doc = {
       first_name,
       last_name,
       email,
       job_title,
       company_name,
       website_name,
       help,
       services,
       info,
     };
     await collection.insertOne(doc);

     await client.close();

     return NextResponse.json("Data has been saved to MongoDB");
   } catch (error) {
     console.error("Error saving data to MongoDB:", error);
     return NextResponse.json("Data has not been saved");
   }
 } else {
   return NextResponse.json("Method not allowed");
 }
}

"I tried to use ChatGPT and received help, but the data is not being stored in my database. When I use req.body console log, it returns null. I searched for solutions online and found many tutorials on YouTube, but they all use Mongoose, which I don’t want to use. If anyone can help, please let me know. I can also provide the client-side code if needed. I used a letter for my environment, so I hid the URI that I wrote.

output"

{"_id":{"$oid":"662570bb7dfc4586e4208c18"},"first_name":null,"last_name":null,"email":null,"job_title":null,"company_name":null,"website_name":null,"help":null,"services":null,"info":null}

fontend code how to go

async function onSubmit(data: z.infer<typeof FormSchema>) {
    console.log(data);
    try {
        setLoading(true);
        const res = await fetch("/api/contact", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data),
        });

        if (!res.ok) {
            throw new Error("Something went wrong");
        }

        setSubmitted(true);
    } catch (error) {
        toast({
            title: "Error",
            description: "Something went wrong",
        });
    } finally {
        setLoading(false);
    }
}

2

Answers


  1. That backend code looks correct, apart from maybe I would suggest throwing an error if the url env var is not defined.

    The logging returning null suggests that you are not calling the endpoint correctly from your frontend.

    Login or Signup to reply.
  2. I see: you want to get data that you putted from FE, right?

    this is solution for NextJS BE:

    const POST = async (request) => {
      const { first_name, last_name } = await request.json();
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search