Is it possible to add a sub collection to a collection without creating document in firestore in android?

12,272

Solution 1

It is possible to add sub collection to collection without creating document in firestore in android?

Definitely not! According to the official documentation, the only structure that is permited is as follows:

db.collection('coll').doc('doc').collection('subcoll').doc('subdoc')

There is no way in Firestore to store a collection beneath other collection. So the following line of code is not allowed:

db.collection('coll').collection('subcoll').doc('subdoc') //Not allowed

As there is no way to store a document beneath other document.

db.collection('coll').doc('doc').doc('subdoc') //Not allowed

Solution 2

The answer from Alex is mostly correct, except he doesn't point out that you can have a subcollection under a document that doesn't exist. There is no obligation to have an actual document in order to have subcollections under its document ID.

When you create a reference to a subcollection using a document id like this:

db.collection('coll').doc('doc').collection('subcoll')

If document id doc doesn't already exist, that's not a problem at all. In fact, after adding documents to subcoll, doc will appear in the Firebase console in italics, indicating that it doesn't exist. There is still an opportunity to create the document, if you wish, but there is no obligation to do so. You can reach into the contents of the subcollection whether or not the document exists. If you create the document, you can also delete it, and all of its subcollections will still exist.

If this organization of subcollections suits your needs, feel free to use it.

Share:
12,272
Gopinathan B
Author by

Gopinathan B

Android developer with 4+ years of experience in mobile development. LinkedIn Account https://www.linkedin.com/in/gopinathan-b-a7b19384/ Play Store Account https://play.google.com/store/apps/developer?id=Gopinathan+B Github Account https://github.com/Gopi1202

Updated on June 11, 2022

Comments

  • Gopinathan B
    Gopinathan B about 2 years

    I am new to cloud firestore in firebase. In my project I created category as collection which is common to all users. But I need to create category as sub collection for each collection. Is it possible?

    Any help will be highly appreciated.