Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firestore subscribe to subcollection that might not yet exist

I’ve got a firebase app where users share a calendar. My firestore collection is structured as follows:

calendarEvents/{year}/monthName/{documentId}

How do I subscribe users to a certain subcollection, say

calendarEvents/{2022}/May

that might not even exist yet, as nobody has created an event for May yet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If not possible (I don’t think it is), how to gracefully achieve such a behavior? The only thing that comes to mind is having separate collection with a single special document that tracks populated months for each year, so basically:

populatedMonths/{theOnlyDocInTheEntireCollection}: {
2021: [1, 2, 5, 12];
2022: [1, 2, 3, 4 ];
}

>Solution :

You can add onSnapshot() listener to collections that do not exist. The querySnapshot returned by listener would just be empty in such cases:

db.collection("col/doc/subcol").onSnapshot((querySnapshot) => {
  console.log(`${querySnapshot.size} documents`)
  // If 0, then collection is either missing or is empty
  // else collection exists and has documents, render them in UI
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading