How to check if the fields exist in a document

I have a user collection and I’m trying to search if the first and last name exists and if not, I just want to put a display message that it does not exist. I tried this but it does not work, it will run the catch phrase.

 async function readUser() {
    try {
      const q = query(
        collection(db, "users"),
        where("firstName", "==", firstName),
        where("lastName", "==", lastName)
      );
      const docSnap = await getDoc(q);

      if (docSnap.exists()) {
        console.log("Document data:", docSnap.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }

    } catch (err) {
      console.log("cannot add user");
    }
  } 

>Solution :

First, if you are executing a query you should use getDocs(). The getDoc() is used to fetch a single document only. You’ll then get a QuerySnapshot that does not have a exists property. If you can instead check if the query returned an empty response (i.e. no matching document) using empty property. Try refactoring the document as shown below:

async function readUser() {
  try {
    const q = query(
      collection(db, "users"),
      where("firstName", "==", firstName),
      where("lastName", "==", lastName)
    );

    const querySnap = await getDocs(q);

    if (querySnap.empty) {
      console.log("No matching document, name available");
    } else {
      console.log("Name found", querySnap.docs.map((d) => d.data()));
    }
  } catch (err) {
    console.log("cannot add user");
  }
}

Leave a Reply