英文:
How do I allow duplicate key for MongoDB in Spring Boot Project?
问题
这是我的文档的外观:
@Getter
@Document(collection = "team")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Team extends BaseTimeEntity {
....
private List<User> designers = new ArrayList<>();
....
}
继承自这个类的BaseTimeEntity
看起来像这样:
@Getter
public abstract class BaseTimeEntity {
@MongoId
private ObjectId id;
@CreatedDate
@Field(name = "created_date")
private LocalDateTime createdDate;
@LastModifiedDate
@Field(name = "modified_date")
private LocalDateTime modifiedDate;
@Field(name = "is_deleted")
protected Boolean isDeleted;
@Field(name = "schema_version")
protected String schemaVersion = "1.0";
}
在将单个Team
数据添加到数据库后,当我尝试使用这个类创建新数据,再次将designers
列表留空时,我遇到了org.springframework.dao.DuplicateKeyException
。
这是我收到的错误消息:
org.springframework.dao.DuplicateKeyException: 服务器localhost:27017上的写入操作错误。写入错误:WriteError{code=11000, message='E11000重复键错误集合:gabojait.team索引:designer.username重复键:{designer.username:null}', details={}};嵌套异常是com.mongodb.MongoWriteException:服务器localhost:27017上的写入操作错误。写入错误:WriteError{code=11000, message='E11000重复键错误集合:gabojait.team索引:designer.username重复键:{designer.username:null}', details={}}。
如何解决这个问题?
英文:
This is how my document looks like
@Getter
@Document(collection = "team")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Team extends BaseTimeEntity {
....
private List<User> designers = new ArrayList<>();
....
}
The BaseTimeEntity
, which is extending from this class, looks like this.
@Getter
public abstract class BaseTimeEntity {
@MongoId
private ObjectId id;
@CreatedDate
@Field(name = "created_date")
private LocalDateTime createdDate;
@LastModifiedDate
@Field(name = "modified_date")
private LocalDateTime modifiedDate;
@Field(name = "is_deleted")
protected Boolean isDeleted;
@Field(name = "schema_version")
protected String schemaVersion = "1.0";
}
After adding a single Team
data into the database. When I try to create a new data with this class, leaving the designers
list blank again, I get org.springframework.dao.DuplicateKeyException
.
This is the error msg that I get.
org.springframework.dao.DuplicateKeyException: Write operation error on server
localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error
collection: gabojait.team index: designer.username dup key: { designer.username: null }',
details={}}.; nested exception is com.mongodb.MongoWriteException: Write operation error
on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate
key error collection: gabojait.team index: designer.username dup key: {
designer.username: null }', details={}}.
How do I fix this problem?
答案1
得分: 0
你的集合在设计师用户名字段上定义了一个索引。移除它或为用户名提供唯一值,或在索引上允许非唯一选项。
英文:
your collection has an index defined on the designer.username field. remove it or provide a unique value to the username, or allow non-unique option on the index.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论