简体   繁体   中英

How to check whether field exists or not in the firestore document?

Even though if(doc.exists) works perfectly, But if there is no data on a specific letter which i clicked, It does not show the console message - console.log("There is a no song which starting with clickedletter");

For example - If I clicked button "A" and imaging there is a song which starting letter "A". This data pop up quickly, But When I clicked button "T" which Data does not exist in the firestore document is not showing console message.

function getID(a){
    console.log("youclicked", a.id);
    var id = a.id;
    //getting this "a" value from an alphabetic pagination bar----------
    const clickedletter = a.getAttribute('value');
    var Aristid = sessionStorage.getItem("getArtistID");
    console.log("current artist ID "+ searchforid);

    db.collectionGroup('MP3_Songs').where("Idofartist", "==", Aristid).orderBy("Song_name").startAt(clickedletter).endAt(clickedletter +'\uf88ff').get().then((documentSnapshot) =>{
          documentSnapshot.forEach(doc=> {
            if(doc.exists){
               
               const data = doc.data();
              console.log("start with clickedletter", data);
              gotdata.innerText = "Song name: " + data.Song_name;
            } else{

             // this is the problem I got. This console log does not show if there is no data.---
                console.log("There is a no song which starting with clickedletter");
            }
      
            })
      
      
      
        }).catch(function(error) {
          console.log("Error getting document:", error);
      });

}

You should add a check to see if there are no documents in the entire result set, which is a QuerySnapshot type object. It has a property called empty .

    db.collectionGroup('MP3_Songs').where("Idofartist", "==", Aristid).orderBy("Song_name").startAt(clickedletter).endAt(clickedletter +'\uf88ff').get()
    .then((querySnapshot) => {
        if (querySnapshot.empty) {
            // here, there are no documents in the query results
        }
        else {
          // here, you can iterate the documents to find matches
          querySnapshot.forEach(documentSnapshot => { ... })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM