Unexpected E11000 when trying to insert a series of documents using javascript

I want to see whether querying with a array element is faster than querying with a key and its value. So I write this to fill my database.

const { MongoClient } = require("mongodb");
const uri = "mongodb://admin:123456@localhost:30001/?retryWrites=true";
const client = new MongoClient(uri);

async function run() {
    await client.connect();
    const database = client.db("test");
    const collection = database.collection("array");
    const doc = {
      array: [
        `${Math.floor(Math.random() * 500)}`,
        `${Math.floor(Math.random() * 500)}`,
        `${Math.floor(Math.random() * 500)}`,
    let p = Promise.resolve(undefined);
    for(i = 0; i < 10000; i++) {
      p = p.then(() => collection.insertOne(doc));
    return p;
setTimeout(() => {
}, 120000);

Note that I’m new to programming, so there may be some mistakes and misunderstaindings.
It’s mostly from the example, but after running this I got a promise rejection for E11000 Duplicate Key. I’m not specifying the _id field, so how come? Only one document was inserted correctly. By the way, if I call .then(client.close()) after run(), there will be an MongoTopologyClosedError: Topology is closed. I’m really confused now.

After your call to

doc contains the field _id of the created document. So the second time around you try to insert a document with _id of an exiting document. Hence the duplicate error. You could use a new doc object or clear the _id of the one you have.

Calling insertOne() to insert many documents, just for the purpose of prefilling the database for further testing, is the worst way to do it. Look at insertMany().

Huge thanks for your reminder! That’s a side-effect that is not so obvious.
All problems solved simply by

for (i = 0; i < 1000; i++) {
    p = p.then(() =>
      collection.insertMany([{array: [
        `${Math.floor(Math.random() * 500)}`,
        `${Math.floor(Math.random() * 500)}`,
        `${Math.floor(Math.random() * 500)}`,

I’ll see the difference between insertOne() and insertMany(). Thank you again!