gpt4 book ai didi

java - Mongodb仅更新文档的部分字段后不执行文档更新

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:18 25 4
gpt4 key购买 nike

我使用的是 Spring Boot 版本 1.4.2 和 mongodb 3.4.2

当我在更改文档的属性之一后使用存储库界面保留现有文档时,旧文档将被保存。例如:

@Document(collection="UserDoc)
public class UserDoc{
@Id
private String id;
private String userName;
private String passWord;
private int age;
//getters and setters...
}
@Autowired
private UserDocRepository userDocRepository;
UserDoc userDoc = userDocRepository.findOne("dummyId");
//assume the id passed in is correct and a UserDoc is returned.
//now when i change one of the fields,eg the age and save it back,the old
//value gets persisted,eg if age is 10 and i change it to 5,the old property
//is still persisted to db unless i Create a new UserDoc and copy all the
//properties before it gets persisted with the correct value of 5.
userDoc.setAge(5);
userDocRepository.save(userDoc);//this is supposed to update the document
//with a new value of 5 instead of 10 as it was probably per the assumption.

UserDoc userDocUpdated = new UserDoc();
userDocUpdated.setId(userDoc.getId);
userDocUpdated.setUserName(userDoc.getUserName);
userDocUpdated.setPassWord(userDoc.getPassWord);
userDocUpdated.setAge(5); //this way,the document is updated with 5 as the
//age

userDocRepository.save(userDocUpdated);//this updates it accordingly with
//the desired value of 5 for the age

第一种情况可能是什么问题?可能是 mongodb 或 spring boot 的问题吗?任何见解将不胜感激。

最佳答案

遗憾的是我对java知之甚少,

这就是你正在做的事情:

private UserDocRepository userDocRepository;
UserDoc userDoc = userRepository.findOne("dummyId");
userDocRepository.save(userDoc);//this is supposed to update the document

我认为你应该这样做:

private UserDocRepository userDocRepository;
UserDoc userDoc = userDocRepository.findOne("dummyId");
userDocRepository.save(userDoc);//this is supposed to update the document

如果我错了,请纠正我:)

关于java - Mongodb仅更新文档的部分字段后不执行文档更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com