JavaScript中Firestore查询无结果时如何输出"Not Found"提示
原因说明
Firestore 条件查询返回的 QuerySnapshot 对象仅在请求本身出错时才会进入 catch 分支,无匹配文档属于请求成功但结果为空的场景,不会触发报错。此时QuerySnapshot的empty属性会为true,你之前的代码只有遍历逻辑,空结果下forEach无执行项,因此没有任何输出。
修复后代码
db.collection("test").where('email', '==', "123@test.com").get() .then(function (querySnapshot) { // 新增空结果判断 if (querySnapshot.empty) { console.log("Not Found") return } querySnapshot.forEach(function (doc) { console.log(doc.data()) }); }).catch(function (error) { console.log("Error getting document:", error); });
补充说明
你也可以用querySnapshot.size属性判断返回的文档总数,if (querySnapshot.size === 0)的判断效果和判断empty完全一致。
内容的提问来源于stack exchange,提问作者Ian Barber
相关产品推荐
相关产品推荐

