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.
MongoServerError: E11000 duplicate key error collection: appdb.users
index: email_1 dup key: { email: "ci@example.com" }
code: 11000Common 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
- Use an ephemeral mongod or memory-server so no data persists between runs.
- Drop the database or collections before seeding.
- Ensure seed scripts are idempotent (upsert on the unique key).
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.
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.