Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle a returned Firestore query when there is not such data?

I am trying to pull a user’s information from Firestore by querying the ‘uid’ field of the ‘users’ collection. Which works fine.

The problem is when there is no user with a matching uid, I would like the function to return
false or null so that I can use this function in an if statement to create a user profile

but querySnapshot always returns an object containing meta data even if the query is not successful.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So How can I handle this?

    async function getUserData (uid) {

      const usersRef = collection(db, "users");
      const q = query(usersRef, where("uid", "==", uid));
      const querySnapshot = await getDocs(q);
      console.log(querySnapshot);

      return (querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        if(doc) {
          return doc.data();
        } else {
          console.log('else');
          return false;
        }
      }));
    };

>Solution :

The QuerySnapshot has a property empty that is true when no document matched the query. You can return false if it’s empty is shown below:

// Returns array of matched documents' data
return querySnapshot.empty ? false : querySnapshot.docs.map((d) => d.data()); 

It might be better to use user’s UID as the document ID (if a user can have only one in your use case) so you can fetch a single document by user ID like this:

const userRef = doc(db, "users", uid);
const docSnap = await getDoc(userRef); // not getDocs

return docSnap.data() || false; // .data() if undefined is doc doesn't exist
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading