Firestore group collection query using Flutter

Viewed 5879

I am new in Firestore database. I am using an app using flutter and Firestore. The database structure for my app is like that:

Rooms --Room1-----Reservations.....reservation dates
                              .....reservation dates
        Room2-----Reservations.....reservation dates
        Room3
        Room4-----Reservations.....reservation dates
        Room5-----Reservations.....reservation dates
                              .....reservation dates
                              .....reservation dates

'Rooms' is level 1 collection which holds all the room details. Each of the room data holds the 'Reservations' collection to holds all reservation details(check_in and check_out date) for that room. Now I want to get the list of rooms which are available in a specific date span. How to work with 'group collection query' for this requirement? Or it is possible to do the same by 'group collection query'?

2 Answers

Late but, if anyone comes back to this, now in firestore there is something called collectionGroup query where you can get all subcollections if they have same name. Which can be done as

Firestore.instance.collectionGroup('Reservations').getDocuments()

This will give you the list of all the Reservations across all rooms. Please read in detail about collection group query here in the documentation

Now I want to get the list of rooms which are available in a specific date span.

Given that you store reservations, a room is available when there is no reservation for that time. Cloud Firestore cannot query for the absence of data, so in your current model that query won't be possible.

If you'd store the available slots in each room's Reservations collection, you could query across all Reservations collections to get the available slots across all rooms. But note that the result of this query are documents from Reservations, and not the individual rooms; you will need to load each room separately if you need information from that.

Alternatively, you could store a list of still-available slots in each Room document. With that you could do a regular query across all rooms to see which ones are still available, and then perform an update across the Room document and its Reservations collection in a transaction.

Related