3
votes

I'm creating a "deep" path scheme in Firestore. (6 part path, 3 collections and 3 documents) Something like collection/document/collection/document/collection/document or in a more real world example: comments/{category_name}/videos/{video_id}/usercomments/{auto_generated_id}

So the problem is that Firestore allows adding a document in a nested subcollection for any path for a document that doesn't currently exist. So when adding a user comment document at the end of the path, it will automatically add video_id and category_name documents if they don't already exist, but the documents are empty (or as it says in the console, "don't exist") and thus don't appear in queries or snapshots.

What will happen is that there will be a lot of documents in the usercomments collection, but I can't retrieve a list of video_ids because the documents in the videos collection are technically all "empty".

How can I keep this path logic scheme and still be able to query through the higher level documents that have no fields? Is there a way to check when adding the comment if the video_id currently exists and if not simply add a field like boolean exists: true?

EDIT: I'm guessing the only way will be to add the field exists: true via cloud functions when the document is created, but I'm not sure if creating the document in the subcollection of the new document from the client will trigger the function for creating the higher level doc or not. I'll update once I find out this out.

UPDATE: Thanks to @Renaud Tarnec for the info, I was able to make a cloud function that will set the higher level documents with a field so that they "exist"/are actually created. Turns out you can extract all the wildcards from the context of the nested document path in the function to dynamically edit higher level documents fields correctly.

1

1 Answers

5
votes

Actually, the following statement in your question is not exact: "it will automatically add video_id and category_name documents if they don't already exist".

If you create a document directly under a usercomments collection with the full path comments/{category_name}/videos/{video_id}/usercomments, no intermediate documents will be created (i.e. no comment or video docs).

The Firebase console shows them in italics in order to "materialize" the hierarchy and allow you to navigate to the usercomment doc but they don't exist in the Firestore database.

Let's take an example: Imagine a doc v1 under

comments/cat1/videos/v1

and another one uc1 under

comments/cat1/videos/v1/usercomments/uc1

Actually, from a technical perspective they are not at all relating to each other. They just share a part of their path but nothing else. One side effect of this is that if you delete a document, its sub-collections still exist.

So, if you want to be able to query for these parent documents, you will have to create them yourself.