MongoDB Embedded Objects have no ID (null value)

后端 未结 4 1200
执念已碎
执念已碎 2020-12-08 07:16

I have a question regarding MongoDB with Spring Data. I have these domain classes:

@Document
public class Deal  {
    @Id
    private ObjectId _id;
    priv         


        
4条回答
  •  情书的邮戳
    2020-12-08 07:53

    In the context of a REST architecture it makes all the sense that nested docs have their own Ids.

    1. Persistence implementation should be independent from resource representation. As an API consumer I don't care if you are using mongo or mysql. If you a nest docs without id in mongo try to imagine how to change the persistence layer to a relational data base. Now do the same exercise having thought beforehand with an implementation independent approach. Modeling nested docs in a relational db, root and nested docs will be different entities/tables each with their own ids. The root could have a one to many relationship with the nested doc.
    2. I may need to access a nested doc directly instead of sequentially.I may not need absolute unique ids, like those issued by mongo, but I'll still need some local unique identifier. This is, unique within the root doc.

    Having argued my point about the need of ids in nested docs @dcrosta has already given a correct answer on how to populate the _id field in mongo.

    Hope this helps.

提交回复
热议问题