Miguel Stevens
Miguel Stevens

Reputation: 9211

Firestore subcollection or foreign key

I'm using Firestore, and I don't see the benefit in using a subcollection versus using a 'foreign' key. When I get a document, the subcollection isn't loaded with that document.

What would be the benefit of using a subcollection, for example

books: {
    1: {
        "name": "Book 1"
     }
}
comments: {
    "bookId": 1,
    "content": "good book"
}

Or using a subcollection

books: {
    name: "Book 1",
    comments: [{...}]
}

Upvotes: 2

Views: 1895

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138834

When I get a document, the subcollection isn't loaded with that document.

This is because the queries in Firestore are shallow: they only get items from the collection that the query is run against. There is no way to get documents from a top-level collection and a subcollections in a single query. Firestore doesn't support queries across different collections in one go.

What would be the benefit of using a subcollection

The benefit is that you can create an unlimited number of documents. In case of storing data in a document, keep in mind the documents have limits. So there are some limits when it comes to how much data you can put into a document. According to the official documentation regarding usage and limits:

Maximum size for a document: 1 MiB (1,048,576 bytes)

As you can see, you are limited to 1 MiB total of data in a single document. When we are talking about storing text, you can store pretty much but if you decide to store complex objects, be careful about this limitation.

Upvotes: 1

wamba kevin
wamba kevin

Reputation: 309

The advantage to using the sub-collections is that you gather information about the collection in itself, and you must use this approach if you do not need to retrieve all the sub collections at once. for example: a user and his articles of blog: if you must be able to retrieve the articles of all the users you use the relations with the foreign key but for the comments you use the sub-collections for a better organization of your database.

Upvotes: 3

Related Questions