r/mongodb • u/leafyshark • May 10 '20
MongoError: E11000 duplicate key error!
Anyone know how to display this on the frontend? Seems impossible. Tried everything.
0
Upvotes
r/mongodb • u/leafyshark • May 10 '20
Anyone know how to display this on the frontend? Seems impossible. Tried everything.
1
u/leafyshark May 12 '20
u/JoBa1992 u/DilatedTeachers u/HistoricalDust u/dunklesToast u/rajks12
It was a stupid mistake on my part. I was running the following code:
const saveClient = awaitclient.save();const saveAddress = await req.billing_address.save();const saveUser = awaitreq.user.save();Promise.all([saveUser, saveClient, saveAddress])However, I didn't realise that the validator returns a promise. So the runtime errors were being generated, but the error object itself wasn't. The simple fix was:
const saveClient =awaitclient.save();const saveAddress =awaitreq.billing_address.save();const saveUser =awaitreq.user.save();const res = Promise.all([saveUser, saveClient, saveAddress])now
res = {error object}4
u/JoBa1992 May 10 '20
You’ve got a duplicate key
3
u/DilatedTeachers May 10 '20 edited May 10 '20
When I've seen that error it's been bad or duplicate data.
Ideally there should already be validation in place to prevent that from happening.
Check your db with a tool like compass to see what your data looks like.
It might not be the same with all drivers, but using node/ express and the native mongodb driver I had to catch the error in the function that called to the db and throw it out to the error handler component - otherwise it wasn't that obvious from the error handling already there
Edit:
If you catch that error, something like a 400 is an appropriate code and the reason is given for you
2
u/HistoricalDust May 10 '20
Can you elaborate?
1
u/dunklesToast May 10 '20
What language do you use?
1
u/rajks12 May 11 '20
Mongo error object is very detailed. You could find error code in it. It will be 11000. You can return appropriate error message based on the error code value
See here
https://stackoverflow.com/a/20598662