Flutter Web Firebase - Get collection by sub-collection field

374

It sounds like you're looking for a collection group query, which would be a single query that searches across the users of all companies at once.

It'd be a query like:

var query = Firestore.instance.collectionGroup("users").where("Email", isEqualTo: userEmail);
var querySnapshot = await query.getDocuments();
var userDocumentRef = querySnapshot.documents[0];

Also see:

Share:
374
Peter Farrell
Author by

Peter Farrell

Updated on December 17, 2022

Comments

  • Peter Farrell
    Peter Farrell over 1 year

    I am building flutter web app linked with firestore. The database schema is as below:

    Firestore Schema

    Firestore Schema

    My problem is I want to get the user document reference i.e (the company and user id) from just entering the users email address. Below is the code is my getUserRef() method:

    Future<fs.DocumentReference> getUserRef (String userEmail) async {
    
    String comp;
    String id;
    List<String> companies = await companyList();
        for (var i = 0; i < companies.length; i++) {
          store.collection('companies').doc(companies[i]).collection('users').get().
          then((val) {
            val.forEach((user){
              if(user.data()['Email'] == userEmail) {
                comp = user.data()['company'];
                id = user.id;
              }
    
            });
    
          });
    
        }
      fs.DocumentReference ref = store.collection('companies').doc(comp).collection('users').doc(id);
    
    return ref;
     }
    

    My companyList() method is working fine and retrieves a list of all the company doc ids. I can't figure out how to get this working and can't move on with the project without it.

    Any help is appreciated.