I'm working on a Next.js API route that inserts user data into a MongoDB collection. However, whenever I insert a new document, it seems to replace all existing documents in the collection instead of appending a new one.
API Route Code (app/api/create-data/route.ts
):
'use server';import { MongoClient, ServerApiVersion } from "mongodb";import { ObjectId } from "mongodb";import { NextRequest, NextResponse } from "next/server";const uri = process.env.URI;if (!uri) throw new Error("Missing MongoDB URI in environment variables");let client: MongoClient | null = null;async function connectToDB() { if (!client) { client = new MongoClient(uri as string, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, }, }); await client.connect(); console.log("Connected to MongoDB"); } return client;}export async function POST(req: NextRequest) { const requestBody = await req.json(); const data = { ...requestBody, _id: new ObjectId() }; try { const client = await connectToDB(); const db = client.db("db1"); const result = await db.collection("ewan").insertOne(data); if (!result.acknowledged) { throw new Error("Failed to insert document"); } return NextResponse.json({ message: "Successfully created account", insertedId: result.insertedId }); } catch (error) { console.error("Database error:", error); return NextResponse.json({ error: "An error occurred while connecting to the database." }, { status: 500 }); }}
Client-Side Code (React):
const handleSubmit= async (event: React.FormEvent) => { event.preventDefault(); const response = await fetch("/api/create-data/", { method: "POST", headers: {'Content-Type': 'application/json', }, body: JSON.stringify({ email: emailRef.current.value, password: passwordRef.current.value, messageToStore: messageToStoreRef.current.value }) }); const data = await response.json(); console.log("API response:", data); };
Every time I insert a new document, it seems like it replaces all existing documents in the "ewan"
collection. I expected each new document to be added instead of replacing existing ones.
What could be causing this issue?
Troubleshooting so far:
- Checked
insertOne()
, which should append, not replace. - Verified
data
structure before insertion usingconsole.log()
. - Ensured that
_id
is generated correctly (new ObjectId()
).