Home > database >  Firebasev9 Firestore Query: Else statement not running
Firebasev9 Firestore Query: Else statement not running

Time:01-12

I'm building an edit profile flow and I hit a huge roadblock. I have User Data stored in a firestore database and I am trying to query the contents of a collection but the if/else statement isn't running.

Here is my current code:

const userQ = query(
      collection(db, "users"),
      where("username", "==", username)
    );
    
const queryName = await getDocs(userQ);

queryName.forEach((doc) => {
      if (doc.exists()) {
        console.log("ERROR. Username taken.");
      } else {
        console.log("User is available");
      }
    }); 

Problem

When a document with the user exists in the collection, it logs the appropriate object to the console. So I know my data structure and routing are correct.

However, when it doesn't exist, nothing gets logged at all, so it totally skips the else statement. I've tried using .length and .size, and nothing has worked.

This question below is basically the same as what I'm asking, but it's for firebase v8 and applying the same ideas did not work for me.

else statement not running after firebase query

Thank you!

CodePudding user response:

If there are no results, calling forEach will have no documents to iterate over. So you can't detect the absence of results with forEach.

Instead, you can use .empty on the result to check if there are no docs matching that username.

Check the code below.

const userQ = query(
      collection(db, "users"),
      where("username", "==", username)
    );
    
const queryName = await getDocs(userQ);

if(queryName.empty){         
        console.log("Username is available");
}
else{
 console.log("Username is already taken.");
}
  • Related