skip to Main Content

Im trying to fetch data from ‘users’ collection from data, where the name of user matches/partially matches the searchQuery. My user document has only 3 fields now, 1.name 2.email 3.uid. Im working with firebase for the first time. Help is much appreciated. Here is the code snippet:

const results: TeamMemberData[] = [];
        const usersRef = collection(db, "users");
        const q = query(usersRef, where("name", ">=", searchQuery));
        const querySnaphot = await getDocs(q);
          querySnaphot.forEach((doc) => {
            console.log(doc.data()); // this logs random user data 

            if (currentUser?.email !== doc.data().email)
              results.push({
                name: doc.data().name,
                email: doc.data().email,
                uid: doc.data().uid,
              });
          });

im logging the results here
I expected to get the results array would have only those users whose name matched in document in firestore.I only types ‘g’ but im getting four users, where, three of them doesn’t even have ‘g’ in their name property.

2

Answers


  1. you got random users because you are using ">=" as Query operators, have a look here how this works when used with strings.


    In your example you need to use the == operator:

    const q = query(usersRef, where("name", "==", searchQuery));
    

    or maybe array-contains operator:

    const q = query(usersRef, where("name", "array-contains", searchQuery));
    

    This query returns every user document where the name field is an array that contains searchQuery. If the array has multiple instances of the value you query on, the document is included in the results only once.

    Login or Signup to reply.
  2. u can also try "in" as includes like :

     const q = query(usersRef, where("name", "in", [searchQuery]));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search