我知道名称相似的问题已经存在,但是他们的解决方案不适用于我的问题,所以无论如何都想提出来。
这是我的User类。如您所见,这里存在一个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的新手,所以,如果我提供的任何内容还不够,请告诉我,以便我也将其发布。
答案 0 :(得分:0)
在执行此代码时,用户名变量以某种方式设置为null。请调试您的代码,并检查为什么使用null值。