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

Node.js + Firestore异常:无法获取指定文档及查询结果不稳定

Firestore写入成功但读取失败/查询结果不稳定的问题解决

问题描述

使用Firestore官方示例代码完成读写操作时,出现异常表现:

  • 文档写入、更新操作成功(Firestore控制台可查看到对应数据)
  • 执行document.get()时抛出错误:error: Did not receive document for "test/mydoc"
  • 集合查询firestore.collection('test').get()结果不稳定,有时能获取到记录,有时返回空结果

测试代码

import { Firestore } from "@google-cloud/firestore";
const firestore = new Firestore({
    databaseId: "(default)"
});
async function main() {
    const document = firestore.doc('test/mydoc');
    await document.set({
        title: 'Welcome to Firestore',
        body: 'Hello World',
    });
    console.log('Entered new data into the document');

    await document.update({
        body: 'My first Firestore app',
    });
    console.log('Updated an existing document');

    const doc = await document.get();
    console.log('Read the document', doc.data());

}

控制台错误输出

Entered new data into the document
Updated an existing document
19 | const document_1 = require("./document");
20 | const util_1 = require("./util");
21 | const logger_1 = require("./logger");
22 | /**
23 |  * A wrapper around BatchGetDocumentsRequest that retries request upon stream
24 |  * failure and returns ordered results.
                              ^
error: Did not receive document for "test/mydoc".

可能的原因及解决方法

  • 调整读取一致性级别
    Firestore默认采用最终一致性读取,刚写入的数据可能存在同步延迟。可以强制使用强一致性读取:

    // 单个文档强一致性读取
    const doc = await document.get({ consistency: 'strong' });
    
    // 集合强一致性查询
    const snapshot = await firestore.collection('test').get({ consistency: 'strong' });
    
  • 检查客户端初始化配置
    如果用本地模拟器,需指定正确的模拟器地址并确保服务正常启动;如果连接云端Firestore,确认认证凭据配置正确:

    // 本地模拟器场景
    const firestore = new Firestore({
        databaseId: "(default)",
        host: "localhost:8080",
        ssl: false
    });
    
    // 云端场景需配置认证凭据,例如通过环境变量指定密钥文件路径
    // export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-keyfile.json"
    
  • 排查本地模拟器问题
    使用Firestore本地模拟器时,可能存在数据缓存或同步问题:

    • 重启模拟器并清空原有测试数据后重新运行代码
    • 确认模拟器版本与@google-cloud/firestore客户端版本兼容
  • 更新客户端依赖版本
    可能存在版本兼容性bug,尝试升级到最新稳定版:

    npm install @google-cloud/firestore@latest
    
  • 确保异步逻辑执行完整
    检查main函数是否被正确调用,且错误处理逻辑到位:

    main().catch(err => console.error('执行出错:', err));
    

内容的提问来源于stack exchange,提问作者mr subject

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:27:44