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

Firestore中无法通过文档ID删除产品,请求技术支援

问题解决:Firestore无法通过文档ID删除产品

核心错误分析

你的删除函数存在关键逻辑错误:完全没必要先获取整个products集合的快照,且用snapshot.docs[product.id].id获取文档ID的方式完全错误——如果product.id是Firestore生成的字符串类型ID,用它作为数组索引会直接导致无法定位到正确的文档对象,自然无法执行删除操作。

实际上你已经在product对象中持有了目标文档的ID,直接用它构建Firestore文档引用即可完成删除。

修正后的删除函数代码

const deleteProduct = async (e: React.MouseEvent<HTMLButtonElement>, product: IProduct) => {
    e.preventDefault()
    try {
      // 直接用已有product.id构建文档引用,无需请求集合快照
      const productRef = doc(db, "products", product.id)
      await deleteDoc(productRef)
      props.onSubmit()
      // 成功提示应使用对应类型的toast
      toast.success('Product was deleted successfully', {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        draggable: true,
      })
      // 重新拉取产品列表更新UI
      getProducts()
    } catch (e) {
      console.error("Error removing document: ", e)
    }
}

额外注意事项

  • 确认product.id的正确性:检查前端获取产品列表时,是否将Firestore文档的doc.id正确赋值给了product.id字段。
  • 移除冗余请求:原代码中getDocs(collection(db, "products"))属于无效操作,会额外消耗网络资源,直接删除即可。
  • 提示类型修正:原代码用错误提示组件展示成功信息,改为toast.success更符合用户交互逻辑。

内容的提问来源于stack exchange,提问作者Andrii Chykulai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:23:23