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

Firestore loadBundle仍存储已删除文档的问题求助

Firestore Bundle缓存同步问题

问题复现流程

  • 初始创建包含3个文档的Firestore Bundle。
  • 删除其中2个文档后重新生成Bundle,此时新Bundle仅含1个文档,但应用本地缓存仍保留最初的3个文档。
  • 重新下载新Bundle的代码实现:
const resp = await fetch(downloadUrl);
await loadBundle(db, resp.body); // 返回{totalDocuments: 1},符合预期
const query = await namedQuery(db, `my-bundle-query`);
if (query) {
   const snap = await getDocsFromCache(query); // 异常:实际返回3个文档,预期仅1个
}

问题补充

  • namedQuery会查询整个本地缓存,而非仅与当前Bundle关联的文档,导致即使设置了4个文档的查询限制,仍会返回超出数量的结果。
  • 官方Firestore Bundle示例存在同样问题。

解决方法

1. 手动清理旧Bundle关联的缓存文档

在加载新Bundle前,通过自定义标记(生成Bundle时为文档添加bundleId字段)定位并删除缓存中属于旧Bundle的文档:

// 定位旧Bundle关联的文档
const oldBundleDocsQuery = query(collection(db, "你的集合名"), where("bundleId", "==", "旧BundleID"));
const oldDocsSnap = await getDocsFromCache(oldBundleDocsQuery);
// 批量删除旧文档
oldDocsSnap.forEach(doc => {
  deleteDoc(doc.ref);
});
// 加载新Bundle
const resp = await fetch(downloadUrl);
await loadBundle(db, resp.body);

2. 给查询添加Bundle ID过滤条件

修改查询逻辑,添加当前Bundle ID的过滤规则,确保仅获取目标Bundle关联的文档:

const targetBundleId = "新BundleID";
// 基于namedQuery添加过滤条件
const filteredQuery = query(
  namedQuery(db, `my-bundle-query`),
  where("bundleId", "==", targetBundleId)
);
const snap = await getDocsFromCache(filteredQuery); // 仅返回当前Bundle的文档

3. 重置Firestore本地缓存(极端场景)

若上述方法无效,可重置整个本地缓存后重新加载Bundle:

await clearIndexedDbPersistence(db);
// 重新加载新Bundle
const resp = await fetch(downloadUrl);
await loadBundle(db, resp.body);

4. 提交官方反馈

这属于Firestore Bundle功能的设计缺陷,可通过Firebase官方支持渠道提交反馈,推动官方优化loadBundle逻辑,使其自动处理已删除文档的缓存清理。


内容的提问来源于stack exchange,提问作者Valera Kvip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:38:26