I am using Spring-Boot 1.5.1
and MongoDB 3.4.6
I've a MongoDB
document which has some @Indexed(unique=true)
annotation on some field.
@Document(collection="Product")
public class Product{
@Id
private String id;
@Indexed(unique=true)
private String name;
@Indexed(unique=true)
private String searchName;
When there is any duplicate name or searchName it throws org.springframework.dao.DuplicateKeyException
.
Stacktrace :
Caused by: org.springframework.dao.DuplicateKeyException: E11000 duplicate key error index: Product.name dup key: { : "name" }; nested exception is com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: Product.name dup key: { : "name" }
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:52)
How can we get the key on which the the exception was thrown.
Something like when we put @NotNull(message = "Product briefDescription cannot be null")
on some filed and it gives you the message
in the exception
, but there is no message
attribute for @Indexed
annotation.
Any way to do it?
The exception message has the information that you're asking for, it includes both the name of the index for which the error was thrown (in your case Product.name
or Product.searchName
).
Unfortunately you'll have to parse that information out of the message. This limitation has been raised elsewhere:
Robustly retrieve which field caued 'duplicate key error' in Mongo
And in the following JIRA tickets:
However, in your example (with the duplicate being the null), I would strongly suggest that you push as much validation as possible down at the client level and not rely on the database to handle any validations that can be done at the client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With