Querying Firestore using 2 where clause in flutter

Viewed 1251
  • I have two attributes in my eventClick table eventID and userID so what I am trying to do is if eventID and userID normally exists then show You have already clicked if not then make an entry of the click. I thought of using two clause and merging it but that just resulted in insertion of the values.
  • I am trying using the below code
final checkSnapshot = FirebaseFirestore.instance
  .collection('eventClick')
  .where('eventID', isEqualTo: eventID)
  .where('userID', isEqualTo: userID)
  .snapshots();
  • I want the working to be like
  if (checkSnapshot.exists) {
      print('already exists');
    } else {
      FirebaseFirestore.instance.collection('eventClick').add({
        'eventID': eventID,
        'eventName': eventName,
        'eventImageUrl': eventImageUrl,
        'userID': userID
      });
    }
2 Answers

Can you try using .get() ? That should return a QuerySnapshot which has a 'size' property. If 0, that means no such document exists.

FirebaseFirestore.instance
  .collection('eventClick')
  .where('eventID', isEqualTo: eventID)
  .where('userID', isEqualTo: userID)
  .get()
  .then((checkSnapshot) {
    print(checkSnapshot.docs[0]);
    if (checkSnapshot.size > 0) {
      print("Already Exists");
    } else {
      //add the document
    }
  });
FirebaseFirestore.instance
                .collection('task')
                .where('usergroup', isEqualTo: 'software')
                .where('userid', isEqualTo: 'ep434334')
                .snapshots(),
Related