从Empty集合中获取查询快照文档的长度

时间:2020-06-02 19:59:08

标签: javascript firebase google-cloud-firestore

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

我的代码::

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

  }

1 个答案:

答案 0 :(得分:1)

问题是您只能访问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的代码,这也是唯一实际需要文档数据的代码。