You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:57:03