Are there any benefits of using subcollections in firestore?

前端 未结 2 632
旧时难觅i
旧时难觅i 2020-12-29 04:53

I have a subcollection for each doc in the users collection of my app. This subcollection stores docs that are related to the user, however they could just as well be saved

2条回答
  •  心在旅途
    2020-12-29 05:46

    The only potential technical advantage to sub-collections that I can think of relates to document size -- it allows you to omit a reference to the parent element. (i.e. for each related rootDocument -> subCollection, there is a single pointer from the root collection document to the subcollection).

    Subcollection

    /messages
    |
     --> /messages/tags
    

    When tags are a sub-collection then they don't need to save the messageId because you access the tags through message document:

    collection("messages").document(messageId).collection("tags")
    

    Root collection

    /messages
    /tags
    

    With a root tags collection each tag would need to store messageId. This basically flips the direction of the pointers.

    collection("tags").whereEqualTo("messageId", messageId)
    

    Summary

    Sub-collection: pointers go from one -> many

    Root collection: pointers go from many -> one

提交回复
热议问题