Firebase出现9 FAILED_PRECONDITION错误,定时删除旧文档功能失效如何解决
Firebase Cloud Function 定时删除旧文档报错解决方案
9 FAILED_PRECONDITION: The requested snapshot version is too old错误本质是查询获取文档快照后,没有在Firestore允许的有效期内完成后续操作,通常由云函数提前终止、操作耗时过长导致。
现存问题
- 云函数提前终止:当前代码直接
return null,没有等待Firestore查询、删除等异步操作完成就结束了函数执行,云函数运行环境会直接中断未完成的异步任务,导致快照还没处理就过期。 - 时间变量逻辑错误:代码中
today变量没有在函数内部定义,大概率是全局静态变量,不会随着每次函数运行更新时间,会导致查询条件不符合预期,甚至拉取到过多不需要处理的文档拉长操作时间。 - 删除操作效率低:逐个生成删除Promise的方式在文档量稍大时耗时过长,也会触发快照过期问题。
修复后代码
exports.removeOldBattles = globalFunctions.runWith(runtimeOpts).pubsub.schedule('every 1 minutes').onRun((context) => { // 函数内部动态计算昨日时间戳,保证每次运行查询条件正确 const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const coll = db.collection("Battles").where("timeStamp", "<", yesterday); // 返回整个异步Promise链,让云函数等待所有操作完成再结束 return coll.get().then(async function (querySnapshot) { // 用Firestore Batch批量操作减少请求次数,单批次最多支持500个操作 let batch = db.batch(); let operationCount = 0; const batches = []; querySnapshot.forEach(function (doc) { batch.delete(doc.ref); operationCount++; // 每满500个操作就新增一个批次 if (operationCount === 500) { batches.push(batch.commit()); batch = db.batch(); operationCount = 0; } }); // 提交最后不足500的批次 if (operationCount > 0) { batches.push(batch.commit()); } await Promise.all(batches); mailMessage("Battles Removal!", "This is a confirmation of battle removal."); console.log("Yesterday battles successfully deleted!"); }).catch(function (error) { mailMessage("Failed Battles Removal!", "This is a confirmation of failed battle removal."); console.error("Error getting battle snapshots: ", error); // 抛出错误保证云函数能正确记录失败状态 throw error; }); });
大文档量可选优化
如果Battles集合单次符合删除条件的文档超过1000条,可做额外优化:
- 给
timeStamp字段加索引,加快查询速度 - 改用游标分页查询,每次查询最多拉取500条处理,避免单次查询拉取过多数据导致快照过期
内容的提问来源于stack exchange,提问作者Shina
相关产品推荐
相关产品推荐

