user12275827
user12275827

Reputation:

MongoDB: Can _id be used to reference another object in a One-to-one relationship?

Let's suppose we have two classes, Class A and Class B. Each Class A is created with a random ObjectID, generated by MongoDB. It can only have a ClassB associated, but can also have none aswell.

Class B on the other hand, when created, must be associated with a existing Class A, and can only have one Class A associated.

In this case, should the _id of Class B be the same as class A, or that is bad pratice, and just like class A, the _id should be generated by MongoDB and another field should reference to the associated to Class A?

In other words, what is correct, example 1 or 2?

Class A

{
    "_id": "5ec6f2b8df6300002e004292",    // ID generated by MongoDB
    "extra info": "extra info goes here"
}

Example 1

Class B

{
    "_id": "5ec6f2b8df6300002e004292",  // Associated ClassA is referenced by _id
    "extra info": "extra info goes here"
}

Example 2

Class B

{
    "_id": "5ec6f2e0df6300002e004293",    // ID generated by MongoDB
    "classA: "5ec6f2b8df6300002e004292",  // Class A is referenced by another field
    "extra info": "extra info goes here"
}

Upvotes: 1

Views: 201

Answers (1)

D. SM
D. SM

Reputation: 14480

Both approaches are possible.

The issue with example 1 is it won't be (easily) possible to decouple A and B if you decide to have them separate down the road for whatever reason.

Upvotes: 1

Related Questions