Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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");
    }
  } 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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");
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!