如何在Firestore文档不存在时主动抛出错误?
问题:Firestore删除预约文档时,如何在文档不存在时抛出错误
现有一段用于取消预约并删除Firestore中accounts集合对应文档的JavaScript代码:
const cancel = (id) => { if(window.confirm("Are you sure to cancel this appointment ?")) { const userDoc = doc(db, 'accounts', id) deleteDoc(userDoc) } }
需求:实现当目标Firestore文档不存在时抛出错误,该如何修改?
解决方案
Firestore的deleteDoc方法本身不会在文档不存在时抛出错误,所以需要先主动查询文档是否存在,再执行后续操作。修改后的代码如下:
const cancel = async (id) => { if(window.confirm("Are you sure to cancel this appointment ?")) { const userDoc = doc(db, 'accounts', id); // 获取文档快照,验证是否存在 const snapshot = await getDoc(userDoc); if (!snapshot.exists()) { throw new Error("目标预约文档不存在"); } // 文档存在则执行删除 await deleteDoc(userDoc); } }
关键说明:
- 将
cancel声明为async函数,因为需要等待Firestore的异步查询/删除操作完成 - 通过
getDoc获取目标文档的快照,用snapshot.exists()判断文档是否存在 - 若文档不存在,直接抛出自定义错误;存在则执行删除逻辑
- 调用该函数时,建议用
try/catch捕获错误(包括网络异常、权限问题以及我们抛出的文档不存在错误),示例如下:
// 调用cancel函数的示例 try { await cancel('你的文档ID'); alert("预约取消成功"); } catch (error) { alert(error.message); }
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

