如何在 spring-data-mongodb 中获取失败的 @Indexed(unique=true)

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

我正在使用 Spring-Boot 1.5.1MongoDB 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") 放在一些字段上,它给你 exception 中的 message,但是 [=23] 没有 message 属性=] 注释。

有什么办法吗?

据我所知,您无法直接在错误中获取重复文档的密钥,因为它不是 Mongo 驱动程序的核心功能。如果引发重复键异常,您最好的选择可能是对您的集合执行查找操作。不过,您可以考虑在 Mongo Jira 上开张票,看看开发团队是否有兴趣在将来添加此类功能。

异常消息包含您要求的信息,它包括引发错误的索引的名称(在您的情况下为 Product.nameProduct.searchName)。

遗憾的是,您必须从邮件中解析出该信息。此限制已在其他地方提出:

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

并且在以下 JIRA 票中:

但是,在您的示例中(重复项为空),我强烈建议您在客户端级别尽可能多地进行验证,而不是依赖数据库来处理可以完成的任何验证在客户端。

如果出现复制密钥特殊情况,请发现对您的积累的操作。 如果您需要查看记录的真实密钥,请查询 system.indexes,例如:

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