我正在从集合日志中获取文档长度。如果集合中有文档,那么是非常好的,但是当集合为空时,它不会给出任何响应。在本例中,我希望它返回或空。
我的代码:
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
})
}发布于 2020-06-02 20:06:22
问题是,您只访问中的长度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 => {块中唯一的代码是打印文档ids的代码,这也是真正需要文档数据的唯一代码。
https://stackoverflow.com/questions/62160415
复制相似问题