Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get which @Indexed(unique=true) is failed in spring-data-mongodb

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?

like image 283
Mehraj Malik Avatar asked Jan 29 '23 13:01

Mehraj Malik


1 Answers

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:

  • https://jira.mongodb.org/browse/SERVER-4637
  • https://jira.mongodb.org/browse/SERVER-19281

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.

like image 55
helmy Avatar answered Feb 01 '23 03:02

helmy