代码之家  ›  专栏  ›  技术社区  ›  Mehraj Malik

如何在spring数据mongodb中获取哪个@Indexed(unique=true)失败

  •  4
  • Mehraj Malik  · 技术社区  · 7 年前

    我正在使用 Spring-Boot 1.5.1 MongoDB 3.4.6

    MongoDB 有一些 @Indexed(unique=true) 某些字段上的注释。

    @Document(collection="Product")
    public class Product{
        @Id
        private String id;
        @Indexed(unique=true)
        private String name;
        @Indexed(unique=true)
        private String searchName;
    

    当有任何重复名称或搜索名称时,它抛出 org.springframework.dao.DuplicateKeyException .

    堆栈跟踪:

    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)
    

    我们如何获取引发异常的键。

    @NotNull(message = "Product briefDescription cannot be null") 在一些文件上,它给了你 message exception 消息 @Indexed 注释。

    有什么办法吗?

    3 回复  |  直到 6 年前
        1
  •  8
  •   helmy    7 年前

    Product.name Product.searchName ).

    Robustly retrieve which field caued 'duplicate key error' in Mongo

    以下是JIRA门票:

    然而,在您的示例中(副本为null),我强烈建议您尽可能多地在客户机级别下推验证,而不要依赖数据库来处理可以在客户机上完成的任何验证。

        2
  •  0
  •   Nicolas Ducom    7 年前
        3
  •  0
  •   user4861249 user4861249    7 年前

    如果出现复制密钥特例,则发现对累积的操作。

    db.collection('system.indexes').findOne({ ns: 'mean-dev.users', name: 'username_1' }, cb);