E11000 duplicate key error when doing PUT for modifiable resource with Spring Data Rest

不羁的心 提交于 2019-12-06 05:53:41

I have found the root cause finally. That is because I didn't give the version field in my PUT body, and Spring-data-rest may be considered to do some insert operation for the document, hence, there will have E11000 duplicate key error exception being thrown.

But, the main issue is that I shall not have an implementation for the setter of the version field as below:

public void setVersion(Long version)
{
   this.version = version;
}

The version parameter will be null if there has no version field in the body of your PUT request. Just remove this setter or annotate with @JsonIgnore can solve this problem. Spring-data-rest will take care the rest.

An alternative answer that doesn't directly address the OP issue, but others maybe running into.

If you are overriding SDR in a @RepositoryRestController PUT method, it's unlikely that your front end is sending a version property, just as it's unlikely that SPD is sending down a version property.

I'm not sure what the right solution is, but we settled on extracting the etag from the header and putting it on the model before submitting a PUT request to our custom controller.

if (obj && header.etag && _.isInteger(header.etag)) {
  obj.version = parseInt(header.etag, 10);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!