How do I filter data from cloud firestore twice?

Issue

I want to check if a user has a string ’Level’ with any number in his document.

Level: int

If this is the case, the future should return true and false if not.
That’s the code I’m trying it with:

class StufenService{
  String userID;
  StufenService(this.userID);

  final CollectionReference userTodos =
  FirebaseFirestore.instance.collection('userTodos');

  Future checkIfStufeExists() async {
    await userTodos.where('Stufe' is int).get();
    final data = QuerySnapshot.data.documents.where(userID);
    if (data.exists){
      return true;
    } else
      {return false;}
  }
}

First I filter out all users who have ’Level’: int in their firebased document. Then I want to check if the current user is among the users.

The data after the QuerySnapshot is underlined in red:

The getter 'data' isn't defined for the type 'QuerySnapshot'.

Can someone help me to implement my plan?
Maybe the whole thing has to be done differently?

Solution

For cases like this, I find it most useful to keep the FlutterFire documentation and Firestore reference handy. Based on those, you code should be something like:

final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');

Future checkIfStufeExists() async {
  var query = userTodos.where('Stufe', isEqualTo: 42); // First condition
  query = query.where("userId", isEqualTo: userID);    // Second condition
  final querySnapshot = await query.get();             // Read from the database
  return querySnapshot.size > 0;                       // Check if there are any results
}

Answered By – Frank van Puffelen

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *