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



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

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

最新更新