javascript - 从 Empty 集合中获取查询快照文档长度
问题描述
我正在从收集日志中获取文档长度。如果集合中有文档,它绝对可以正常工作,但是当集合为空时它不会给出任何响应。在这种情况下,我希望它返回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
})
}
解决方案
问题是您只能访问语句内的长度。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 的代码,这也是唯一实际需要文档数据的代码。
推荐阅读
- reactjs - 使用 React 从 Express API 获取 JSON 时遇到问题
- netezza - 如何解决 netezza SQL 错误 [1100] [HY000]: ERROR: System is not 'Online'
- javascript - 我想在单击 btn 时将样式(特定背景颜色)的元素(跨度或 div)创建到父元素中?
- postgresql - Postgres - 在分组行中使用窗口函数
- php - 为什么数据库返回旧信息?
- javascript - Mongoose 恢复上一个版本
- coq - 无法满足以下约束:在环境中
- python - train_test_split中random_state的意义是什么?
- python - 如何将数据附加到不包含该列表任何键的 JSON 列表?
- mysql - 仅当一个表中的所有行都在另一个表中时,才在 ruby on rails 2.3.3 中加入 MySQL 表