🔧 Error Fixes
· 1 min read

MongoDB: E11000 Duplicate Key Error — How to Fix It


E11000 duplicate key error collection: mydb.users index: email_1 dup key

You’re inserting a document with a duplicate value in a unique index.

Fix 1: Use updateOne with upsert

await db.collection('users').updateOne(
  { email: 'alice@example.com' },
  { $set: { name: 'Alice' } },
  { upsert: true }
);

Fix 2: Check before inserting

const existing = await db.collection('users').findOne({ email });
if (!existing) {
  await db.collection('users').insertOne({ email, name });
}

Fix 3: Handle the error

try {
  await db.collection('users').insertOne(doc);
} catch (err) {
  if (err.code === 11000) {
    console.log('Duplicate email');
  }
}