MongoDB insertOne Replaces Documents Instead of Appending in Next.js API Route

Title: MongoDB insertOne Replaces Documents Instead of Appending in Next.js API Route

Body:

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);
  };

Issue:

  • 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.

Troubleshooting So Far:

  1. Checked insertOne(), which should append, not replace.
  2. Verified data structure before insertion using console.log().
  3. Ensured that _id is generated correctly (new ObjectId()).

What could be causing this issue? Any guidance would be appreciated!

Super strange… I would not expect these results. Sorry you’re having this trouble. If it were me, I’d start introducing console.logs…

Try running these checks:

console.log("Request Body Before Insert:", requestBody);
console.log("Generated Data:", data);
console.log("Existing Documents:", await db.collection("ewan").find().toArray());

This will help us confirm:

  • What’s actually being inserted?
  • Is _id being overwritten?
  • What exists in the collection before inserting?
1 Like

Hello sir, I was able to find a solution. I made a new collection and the existing documents were not being replaced anymore but in the old collection the documents were always getting replaced each inserts. So the problem was in the collection’s setting I think, if then what could be the trouble in the old collection?

This is the code.

console.log("Request Body Before Insert:", requestBody);
console.log("Generated Data:", data);
console.log("Previously Existing Documents:", await db.collection("ewan").find().toArray()); const result = await db.collection("ewan").insertOne(data);
console.log("Current Existing Documents:", await db.collection("ewan").find().toArray());

Thankyou in advance sir.

This are the output of the console logs. So far they had different id but it still replaces it.

Connected to MongoDB
Request Body Before Insert: {
  email: 'sda2d@sadasd.com',
  password: '123123123',
  messageToStore: 'haysasasd'
}
Generated Data: {
  email: 'sda2d@sadasd.com',
  password: '123123123',
  messageToStore: 'haysasasd',
  _id: new ObjectId('67d240bcc544fb8f56534764')
}
Previously Existing Documents: [
  {
    _id: new ObjectId('67d23f7cc544fb8f56534763'),
    email: '120958rectin@depedmarikina.com',
    password: 'taetae',
    messageToStore: 'hays'
  }
]
Current Existing Documents: [
  {
    _id: new ObjectId('67d240bcc544fb8f56534764'),
    email: 'sda2d@sadasd.com',
    password: '123123123',
    messageToStore: 'haysasasd'
  }
]