首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从空集合获取query快照文档长度

从空集合获取query快照文档长度
EN

Stack Overflow用户
提问于 2020-06-02 19:59:08
回答 1查看 660关注 0票数 2

我正在从集合日志中获取文档长度。如果集合中有文档,那么是非常好的,但是当集合为空时,它不会给出任何响应。在本例中,我希望它返回或

我的代码:

代码语言:javascript
运行
复制
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
})

  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-02 20:06:22

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

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

代码语言:javascript
运行
复制
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 => {块中唯一的代码是打印文档ids的代码,这也是真正需要文档数据的唯一代码。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62160415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档