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 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 :

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

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