So, we need to create a 1:1 relationship between two collections: user_collection, profile_collection. The corresponding lab in the “Data Modelling” MongoDB course, suggests two options:
Solution A
user_collection
- _id
- profileId (ref => profile_collection.profileId) [unique index]
profile_collection
- _id
- profileId [unique index]
Solution B
user_collection
- _id
- profileId (ref => profile_collection._id [unique index]
profile_collection
- _id
In the lab concerning 1:1 relationship, it is recommended (it is the only correct answer) to have the relation A (see above).
But… why? With the “solution A” I see the following disadvantages:
- we have to create one additional field - profileId - this will require more disk space to store this bit of info, more ram to keep it in memory while processing;
- we have to create additional index to make sure its uniqueness, that we also need to store both: in the disk and in the RAM
- field _id (in the profile_collection) looses it’s utility, as its role is taken by profileId field.
- for developer it may be confusing which field to use.
While solution B, seems to be a better solution, because:
- it is clear for the developer, that the role of the _id field to is to reflect the profile’s id, because it is read very natively:
const profile = await profilesCollection.findOne();
profile._id // => profile's id
profile.nickname // (etc.) profile's nickname
- _id field inevitably is created with index by default, so not need to crate another index and to keep it in disk and memory.
- no additional field management needed
Well, maybe, there is one small disadvantage in solution B, is that we need to create ‘profile’ before the user. But, we can overcome this by creating value for _id field on the client side.
With all that in mind, I do not understand, why MongoDB’s course teaches students to use “solution A”.
Please, help to understand this.