2

I have a collection with a field 'email' in MongoDB and a unique index on this field. If I try to insert a document with an existing 'email' I get the following error

error:  name=MongoError, message=E11000 duplicate key error index: testDB.users.$email_1 dup key: { : "[email protected]" }, index=0, code=11000, errmsg=E11000 duplicate key error index: testDB.users.$email_1 dup key: { : "[email protected]" }

Is there a proper way to get the exact key name from the error message to help identify the exact key that caused the duplicate key error i.e how to extract the 'email' from the error message above?

1

1 Answer 1

0

Extract filed key

let field = (error.errmsg.match(/[index: ]\w+[_1]/)[0].split('_1')[0]).replace(' ', ''); // return 'email'

or

let field = error.message.split('.$')[1]; // return 'email_1 dup key: { : "[email protected]" }'
field = field.split(' dup key')[0]; // return 'email_1'
field = field.substring(0, field.lastIndexOf('_')); // return 'email'

Extract filed value

let value = (error.errmsg.match(/(["'])(\\?.)*?\1/)[0]).replaceAll('"', ''); // return '[email protected]'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.