Home > Back-end >  How to handle a returned Firestore query when there is not such data?
How to handle a returned Firestore query when there is not such data?

Time:09-18

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.

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;
        }
      }));
    };

CodePudding user response:

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
  • Related