Node.js driver - insertOne inserts two documents

Hey there, I’m running this example code from this docs page. When I run the code the single insertOne call is inserting two documents into the collection. I cannot figure out why this is happening. Here’s the code:

Const dbURI =
  "mongodb+srv://user:password@cluster.xxxxx.mongodb.net/?w=majority";

const { MongoClient } = require("mongodb");

const client = new MongoClient(dbURI, { useUnifiedTopology: true });

async function run() {
  try {
    await client.connect();

    const database = client.db("test");
    const collection = database.collection("testcollection");
    // create a document to be inserted
    const doc = { name: "Red", town: "kanto" };
    const result = await collection.insertOne(doc);

    console.log(
      `${result.insertedCount} documents were inserted with the _id: ${result.insertedId}`
    );
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

Hello @Brian_Cross, welcome to the community.

I ran your code once and found that the script inserted exactly one document into the testcollection:
{ "_id" : ObjectId("5f78450f74c4e534304dadb0"), "name" : "Red", "town" : "kanto" }

It is likely, you ran the code twice and found two documents with same JSON { name: "Red", town: "kanto" }, but different _id values. Note that the _id is created automatically and is a unique value.

If you run the script the second time you will see a second document, with a different _id, for example:
{ "_id" : ObjectId("5f78459981ebc353289476f0"), "name" : "Red", "town" : "kanto" }

Hey @Prasad_Saya, thanks for the welcome and the reply. I don’t think I’m running the code twice but yeah that’s exactly what it looks like. I’m just running it at the command line with node and I’m only getting one console log of the document being created. Very weird. Maybe my system has a bug of some sort. I’ll try it on a different machine later. Thanks again for the reply; much appreciated!

I ran the code from command-line with NodeJS v12.18.3 and MongoDB 4.2.3.