mongodb - Mongo + Spring Boot 应用程序 - E11000 重复键错误
问题描述
我知道已经存在具有相似名称的问题,但他们的解决方案不适用于我的,所以还是想问一下。
这是我的用户类。如您所见,这里存在 subscribedTo 列表,我在其中存储用户已订阅的用户。无论如何,我想向数据库中插入一个用户,但是我得到“E11000 重复键错误”
错误如下
{
"timestamp": "2018-07-22T17:06:20.111+0000",
"status": 500,
"error": "Internal Server Error",
"message": "E11000 duplicate key error collection: newdb.user index: subscribedTo.username dup key: { : null }; nested exception is com.mongodb.MongoWriteException: E11000 duplicate key error collection: newdb.user index: subscribedTo.username dup key: { : null }",
"path": "/user/add"
}
用户类
@Document(collection = "user")
@Data
public class User{
@Id
private String id;
@Indexed(unique = true)
@NotBlank
private String username;
@NotBlank
@Size(min=5, max=32)
private String password;
@Indexed(unique = true)
@Email
private String email;
@CreatedDate
private Date dateRegistered;
@LastModifiedDate
private Date dateLastEntry;
private String profilePictureUrl;
private List<User> subscribedTo;
private int active; //0 for false
public User(@NotBlank String username,
@NotBlank @Size(min = 5, max = 32) String password,
@Email String email,
String profilePictureUrl) {
this.id = UUID.randomUUID().toString();
this.username = username;
this.password = password;
this.email = email;
this.dateRegistered = new Date();
this.dateLastEntry = new Date();
this.profilePictureUrl = profilePictureUrl;
this.subscribedTo = Arrays.asList();
this.active = 1;
}
}
那么,为什么会发生这样的事情呢?我对用户名和电子邮件设置了唯一限制,而不是在列表中。
谢谢,提前。顺便说一句,我对 MongoDb 真的很陌生,所以,如果我提供的任何内容还不够,请告诉我,以便我也会发布它们。
解决方案
在执行此代码时,用户名变量以某种方式设置为 null。请调试您的代码并检查为什么会出现空值。