Home > Software design >  How to check if the fields exist in a document
How to check if the fields exist in a document

Time:05-13

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

CodePudding user response:

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

CodePudding user response:

if I understood your question correctly , I would go and check against the value directly, you can try the following sets of checks and manipulate them depending on your current needs.

if(docSnap.data().firstName && docSnap.data().lastName){
// there is a first and last name !! 
} else {
//either one of those is missing.
}

you can check for either one.

if(docSnap.data().firstName ){
// there is a first name !! 
} 
if(docSnap.data().lastName ){
// there is a last name !! 
} 
if(!docSnap.data().firstName && !docSnap.data().lastName ) {
//Both of those are missing.
}

  • Related