Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add subcollection to a document in Firebase Cloud Firestore

The documentation does not have any examples on how to add a subcollection to a document. I know how to add document to a collection and how to add data to a document, but how do I add a collection (subcollection) to a document?

Shouldn't there be some method like this:

dbRef.document("example").addCollection("subCollection") 
like image 609
rgoncalv Avatar asked Nov 27 '17 15:11

rgoncalv


People also ask

How do I update Subcollection in firestore?

You just need to get a reference to the subcollection, which you get from the DocumentReference . And on that you simply use the regular method for writing data again: firebase.google.com/docs/firestore/manage-data/add-data. If you're having a hard time making this work, update your question to show what you've tried.

What is a Subcollection in firestore?

A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries. You can create a subcollection called messages for every room document in your rooms collection: collections_bookmark rooms.

How do I create a Subcollection in firestore v9?

Firestore doesn't have operations for creating collections and subcollections. You just start writing documents to them, and they will appear in the console. Are you actually asking how to write a document to a subcollection, regardless of whether or not that's previously been done?


2 Answers

Edit 13 Jan 2021:

According to the updated documentation regarding array membership, now it is possible to filter data based on array values using whereArrayContains() method. A simple example would be:

CollectionReference citiesRef = db.collection("cities"); citiesRef.whereArrayContains("regions", "west_coast"); 

This query returns every city document where the regions field is an array that contains west_coast. If the array has multiple instances of the value you query on, the document is included in the results only once.


Assuming we have a chat application that has a database structure that looks similar to this:

enter image description here

To write a subCollection in a document, please use the following code:

DocumentReference messageRef = db     .collection("rooms").document("roomA")     .collection("messages").document("message1"); 

If you want to create messages collection and call addDocument() 1000 times will be expensive for sure, but this is how Firestore works. You can switch to Firebase Realtime Database if you want, where the number of writes doesn't matter. But regarding Supported Data Types in Firestore, in fact, you can use an array because is supported. In Firebase Realtime database you could also use an array, but this is which is an anti-pattern. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write.

Cloud Firestore can store arrays, it does not support querying array members or updating single array elements. However, you can still model this kind of data by leveraging the other capabilities of the Cloud Firestore. Here is the documentation where is very well explained.

You also cannot create a subcollection with 1000 messages and add all of them to the database and at the same time to consider a single record. It will be considered one write operation for every message. In total 1000 operations. The picture above does not show how to retrieve data, it shows a database structure in which you have something like this:

collection -> document -> subCollection -> document 
like image 60
Alex Mamo Avatar answered Sep 24 '22 14:09

Alex Mamo


Here's a variation where the subcollection is storing ID values at the collection level, rather than within a document where the subcollection is a field there with additional data.

This is useful for connecting a 1-to-Many ID mapping w/out having to drill through an additional document:

function fireAddStudentToClassroom(studentUserId, classroomId) {      var db = firebase.firestore();     var studentsClassroomRef =         db.collection('student_class').doc(classroomId)           .collection('students');      studentsClassroomRef         .doc(studentUserId)         .set({})         .then(function () {             console.log('Document Added ');         })         .catch(function (error) {             console.error('Error adding document: ', error);         }); } 

Thanks to @Alex's answer

This answer a bit off from the original question here, where it explicitly asks for adding a collection to a document. However, after searching for a solution for this scenario and not finding any mention in docs or on SO, this post seems like a reasonable place to share the findings

like image 32
Gene Bo Avatar answered Sep 25 '22 14:09

Gene Bo