Как проверить, существует ли поле в документе firestore? - PullRequest
0 голосов
/ 05 августа 2020

Хотя if(doc.exists) работает отлично, но если нет данных по указанной c букве, которую я нажал, сообщение консоли не отображается - console.log("There is a no song which starting with clickedletter");

Например - Если я нажал кнопку «А» и представил себе песню, у которой начинается буква «А». Эти данные появляются быстро, но когда я нажал кнопку «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 голосов
/ 05 августа 2020

Вы должны добавить проверку, чтобы увидеть, нет ли документов во всем наборе результатов, который является объектом типа 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 => { ... })
...