Search code examples
mongodbmongodb-queryforeign-keys

mongodb - storing relation with id


I have a very basic (might be sily) question.
Suppose I am having product collection with list of product as below.

db.products.findOne
{
    "_id" : ObjectId("60db1b449f9a43695c4bb461"),
    "name" : "product 1"
}

while storing category as a relation, how should it be stored? (Please check the category_id)

approach 1

db.products.findOne
{
    "_id" : ObjectId("60db1b449f9a43695c4bb461"),
    "name" : "product 1",
    "category_id" : ObjectId("608f981fcfeaa757ca69b4b5")
}

approach 2

db.products.findOne
{
    "_id" : ObjectId("60db1b449f9a43695c4bb461"),
    "name" : "product 1",
    "category_id" : "608f981fcfeaa757ca69b4b5"
}

Solution

  • It depends.

    Embed as ObjectId type if: You will perform $lookUp operations based on this key, then it's better to embed it as ObjectId type.

    I highly recommend embedding it as ObjectId

    Embed as string type if: The driver or application which you are using does not support working with the ObjectId type.

    In the company I am working for, we have embedded relations as ObjectId, and even though it's easy to pass the data to REST API (since no conversion is needed), it's a big pain to convert string to ObjectId for $lookUp operations.

    Note that in most of the languages, you have to handle errors additionally while converting string to ObjectId (since ObjectId has validation rules), whereas this problem is not present for converting ObjectId to string