首页 > 解决方案 > 从 Empty 集合中获取查询快照文档长度

问题描述

我正在从收集日志中获取文档长度。如果集合中有文档,它绝对可以正常工作,但是当集合为空时它不会给出任何响应。在这种情况下,我希望它返回0null 。

我的代码::

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

  }

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


问题是您只能访问语句的长度。querySnapshot.forEach(doc => {如果没有文档,则永远不会执行该语句中的代码。

无论文档如何都应该运行的任何代码都应该在querySnapshot.forEach(doc => {块之外。例如:

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

现在querySnapshot.forEach(doc => {块内的唯一代码是打印文档 ID 的代码,这也是唯一实际需要文档数据的代码。


推荐阅读