Skip to content
Latchkey

MongoDB "E11000 duplicate key error" in CI

A write violated a unique index: a document with the same key already exists. In CI this typically comes from a database that was not reset between runs, or seed/fixture data inserted twice in the same job.

What this error means

An insert or upsert fails with "MongoServerError: E11000 duplicate key error collection: <db>.<coll> index: <idx> dup key: { ... }", naming the index and duplicated value.

node
MongoServerError: E11000 duplicate key error collection: appdb.users
index: email_1 dup key: { email: "ci@example.com" }
  code: 11000

Common causes

The test database was not reset between runs

A reused mongod volume keeps documents from a prior run, so re-seeding hits the existing unique key.

Seeds or tests insert the same key twice

A fixture runs more than once, or two tests insert the same unique value, tripping the index.

How to fix it

Start each run from a clean database

  1. Use an ephemeral mongod or memory-server so no data persists between runs.
  2. Drop the database or collections before seeding.
  3. Ensure seed scripts are idempotent (upsert on the unique key).
test-setup.js
beforeAll(async () => {
  await db.dropDatabase();
});

Isolate data per test worker

When tests run in parallel, give each worker its own database name so unique keys do not collide.

test-setup.js
const dbName = "appdb_" + (process.env.JEST_WORKER_ID || "0");

How to prevent it

  • Reset or use a fresh database for each CI run.
  • Make seed scripts idempotent with upserts.
  • Namespace databases per parallel worker.

Frequently asked questions

What causes ""E11000 duplicate key error""?
A reused mongod volume keeps documents from a prior run, so re-seeding hits the existing unique key.
How do I fix "E11000 duplicate key error"?
Start each run from a clean database

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card