Home > other >  how to search through firebase
how to search through firebase

Time:09-25

I want to search through my firebase collection and get any document with the specific phonenumber entered, but it keeps returning nothing.

Here is a screensot of my database enter image description here

Here is the code i used to query it:

await FirebaseFirestore.instance
    .collection("users")
    .where("mobilenumber", isEqualTo: " 23407063435023")
    .get()
    .then((QuerySnapshot querySnapshot) { querySnapshot.docs.map((DocumentSnapShot documentSnapshot) {
      if (documentSnapshot.exists) {
        print("found");
      }
    });
}).catchError((error) => throw error); 

and this is the security rule enter image description here

CodePudding user response:

The problem was in then, I should have used foreach instead of a map,

await FirebaseFirestore.instance
  .collection("users")
  .where("mobilenumber",isEqualTo: " 23409056088820")
  .get()
  .then((QuerySnapshot querySnapshot) {
    querySnapshot.docs.forEach((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print(documentSnapshot.id);
      }
  });
                                        
}).catchError((error) {
  print(error);
});

I don't know why though.

CodePudding user response:

Your query searches docs on country, not on phonenumber. Adapt it as follows:

await FirebaseFirestore.instance
    .collection("users")
    .where("phonenumber", isEqualTo: "12345")
    .get()
    .then((QuerySnapshot querySnapshot) { querySnapshot.docs.map((DocumentSnapShot documentSnapshot) {
      if (documentSnapshot.exists) {
        print("found");
      }
    });
}).catchError((error) => throw error); 
  • Related