如何检查Firestore文档中是否存在字段?

时间:2020-08-05 09:43:52

标签: javascript google-cloud-firestore

即使if(doc.exists)工作正常,但是如果我单击的特定字母上没有数据,它也不会显示控制台消息-console.log("There is a no song which starting with clickedletter");

例如-如果我单击按钮“ A”并进行成像,则有一首以字母“ A”开头的歌曲。该数据迅速弹出,但是当我单击“ T”按钮(在Firestore文档中不存在该数据)时,不会显示控制台消息。

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

}

1 个答案:

答案 0 :(得分:0)

您应该添加检查以查看整个结果集中是否为QuerySnapshot类型的对象。它具有一个名为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 => { ... })