首页 > 解决方案 > 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 中创建子文档,我可以轻松找到一些对象并删除或更新它们?

标签: javamongodbspring-boot

解决方案


首先不能在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)
}

如果您将两个实体建模为单独的集合,情况会有所不同。


推荐阅读