DDD and MongoDB: Is it okay to let Mongo create ObjectIDs?

1.7k views Asked by At

According to DDD (Blue book, Evans) a Factory has the responsibility to create an Aggregate Root in a valid state. Does this mean it should be able to create the technical id (objectId in mongoDB world) as well as the domain id?

On the one hand, this seems like a technical detail and it would seem okay to let Mongo handle the creation of the ID.

On the other, enabling querying by id (by having getById in a DDD repository) exposes the technical id to the domain, which in turn would make it the responsibility of the Factory to create it.

Perhaps I can't get my head on the different use-cases / overlap, etc. of Technical Id's vs DomainId's or perhaps I'm being overzealous, but I'd appreciate your opinion anyway.

In short: In DDD: Should a factory be able to create the technical Id as well as the domain Id?

possible implementation: Hi/Lo ( How to set the hilo sequence starting value in MongoDB Norm?)

EDIT: although the hi/lo way exposes the Factory to the persistence layer, which is something only the Repository should know. hmmm

Thanks

1

There are 1 answers

3
eulerfx On BEST ANSWER

Factories don't have to concern themselves with the ID because the validity of an aggregate is orthogonal to identity. Identity can be assigned in a few different ways, either as a incremental ID from a relational database in which case the repository has to manage it, or as a UUID/GUID in which case it can be assigned by the factory, or repository, or even the calling client which is convenient because then the client has the key by default.

Whenever possible, I try to maintain a single identity for aggregates. I'm not sure if MongoDB requires an additional technical ID, but if it does and the domain ID can't be used in its place, then MongoDB should manage it on its own and behind the scenes.