java - Web应用MongoDB数据库结构
问题描述
我在 Spring Boot 中有一个简单的 Web 应用程序来创建 CV 配置文件。Profile 是我的主要模型,我想添加另一个部分 Education,我可以轻松添加、删除和更新该部分的新字段。
Profile.class
@Data
@AllArgsConstructor
@Document(collection = "profiles")
public class Profile {
@Id
private String id;
private String firstName;
private String lastName;
private List<Education> education;
}
Education.class
@Data
public class Profile {
private LocalDate startDate;
private LocalDate endDate;
private String description;
}
添加新的教育对象没有问题,但是在列表中查找要删除或更新的教育对象时遇到问题。
有没有更好的方法在 MongoDB 中创建子文档,我可以轻松找到一些对象并删除或更新它们?
解决方案
首先不能在Education
没有唯一标识符的情况下对实体进行 CRUD 操作。其次,Education
实体的 CRUD 操作(例如通过 REST)总是在父Profile
实体的上下文中完成。这意味着,如果您将两者都建模为一个集合,则Education
实体的更新实际上是文档的更新。Profile
删除教育的伪代码如下所示:
removeEducation(profileId, eductionId) { // you need profileId here
Profile profile = findProfile(profileId)
profile.removeEducationById(eductionId) // updates the document
saveProfile(profile)
}
如果您将两个实体建模为单独的集合,情况会有所不同。
推荐阅读
- junit - Gitlab 测试 JUnit xml 的错误或跳过状态
- ios - 使用自定义图层时删除标签栏背景
- python - 如何使用 Selenium 遍历 web 表?
- firebase - Firebase 分析中的 500 个事件限制
- python - 使用 shapefile 提取 gos-r netcdf 文件的数据
- c# - 将模块属性注入动态注册的组件
- android - JobScheduler - 确定 JobService 是否由于重新调度或首次运行而正在运行
- javascript - d3.js 强制有向树矩阵
- python - 使用 Optuna 进行微调时使超参数加起来为 1
- javascript - 如何跳过匹配 html 属性中的文本?