user2828442
user2828442

Reputation: 2515

Get querysnapshot docs length from Empty collection

I am fetching docs length from collection logs. It works absolutely fine if there are documents in the collection, but it doesnt give any response when collection is empty. I want it to return 0 or null in this case.

My code::

firebase.firestore().collection('logs')
.where("date" , "==" , show_year_month_date)
.get()
.then(querySnapshot => {
 querySnapshot.forEach(doc=> {
 console.log(doc.id, " => ", doc.data());
 alert(querySnapshot.docs.length); // It doesnt goes here if collection is empty
 console.log(querySnapshot.docs.length);

 if(querySnapshot.docs.length==null){
  console.log("its null"); // It doesnt goes here if collection is empty
}

 if(querySnapshot.docs.length>0){
   console.log("entry found");
 }
 if(!querySnapshot.docs.length){
   console.log("no entry");
   alert("no entry"); // It doesnt goes here if collection is empty
   this.sendLogs();
 }
});
})
.catch(function(error) {
   console.log("Error getting documents: ", error);
   alert("error no document found"); // It doesnt goes here if collection is empty
})

  }

Upvotes: 2

Views: 996

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The problem is that you only access the length inside the querySnapshot.forEach(doc => { statement. If there are no documents, the code inside that statement is never executed.

Any code that should run regardless of the documents should be outside of the querySnapshot.forEach(doc => { block. So for example:

firebase.firestore().collection('logs')
    .where("date", "==", show_year_month_date)
    .get()
    .then(querySnapshot => {
        alert(querySnapshot.docs.length);
        console.log(querySnapshot.docs.length);

        if (querySnapshot.docs.length == null) {
            console.log("its null"); // It doesnt goes here if collection is empty
        }

        if (querySnapshot.docs.length > 0) {
            console.log("entry found");
        }
        if (!querySnapshot.docs.length) {
            console.log("no entry");
            alert("no entry"); // It doesnt goes here if collection is empty
            this.sendLogs();
        }

        querySnapshot.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
        alert("error no document found"); // It doesnt goes here if collection is empty
    })
}

Now the only code that is inside the querySnapshot.forEach(doc => { block is the code that prints the document ids, which is also the only code that actually needs the document data.

Upvotes: 3

Related Questions