0

I am working on a flutter app that allows a user to select and book a trip. The data source is Firestore and is configured as follows:

Firestore -- Root
   |
   trips -- collection
     |
     Auto-ID -- Document
       |
       bookings -- collection
          |
          Auto-ID -- Document

There are a list of trip documents that are created with an Auto-ID and placed in the trips collection.

A user can select a trip and make a booking and this creates a document in the bookings collection. (subCollection of trips)

I can get a list of all the bookings for one trip using the following query:

Stream<QuerySnapshot> getAllBookings(document) {
    return db
        .collection('trips')
        .document(document)
        .collection('bookings')
        .snapshots();
}

I can get a booking by one user using the following query:

Stream<QuerySnapshot> getUserBookings(document, user) {
    return db
        .collection('trips')
        .document(document)
        .collection('bookings')
        .where('user', isEqualTo: user)
        .snapshots();
}

But I cannot fathom out how to combine the two to loop over all the trips to find all the trips booked by one user and return this as a stream.

Any help would be much apprciated.

Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
Theo Carper
  • 183
  • 10
  • In the docs it's mentioned that queries in firestore don't support *Single queries across multiple collections or subcollections.* . So you would probably want to change the structure, see https://firebase.google.com/docs/firestore/manage-data/structure-data . The other option would be to first query the trips collections and then for each of its bookings collection look if it has bookings belonging to that specific user and at the end bind all the result into a stream. This would be not only an awkward implementation but very wasteful as well. – user Feb 07 '19 at 15:58
  • FYI you can use the {} button in the editor to properly format blocks of code without having to use backticks. – Doug Stevenson Feb 07 '19 at 16:33
  • @Luksprog thank you for the link, I now know that I am trying to perform a 'collection group query' https://stackoverflow.com/questions/46573014/firestore-query-subcollections which is in the works, but with no timeline. Until then, yes, a top level collection will be the solution. – Theo Carper Feb 07 '19 at 20:05
  • @DougStevenson Thanks for the tip. Now if only I could test my queries in the Firestore console, this would let me test out different data structures to find the optimum one. It would also allow me to understand and test out how queries work in Firestore, would this ever be possible? – Theo Carper Feb 07 '19 at 20:17
  • Yes, the console has a way to perform queries. https://stackoverflow.com/a/38424269 – Doug Stevenson Feb 07 '19 at 20:45

0 Answers0