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

React中使用Firebase V9更新Firestore文档报错求助

问题

我正在React应用中尝试更新Firestore内的文档,目标是更新uid与当前用户ID匹配的文档。我使用的是Firebase V9,代码如下:

if(myDescription.length < 15){
    alert("The description must be longer !")
    return
}

const currentUID = auth.currentUser.uid

const myDoc = doc(collection(db, "descriptions"), where("uid", "==", currentUID))
await setDoc(myDoc, {desc: myDescription})

执行时出现以下错误:

Uncaught (in promise) TypeError: n.indexOf is not a function
    at rt.fromString (index.esm2017.js:1032:1)
    at sa (index.esm2017.js:16044:1)
    at handleClick (Description.js:38:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)

解决方案

问题根源

错误在于将where查询条件直接传入doc()函数。doc()的第二个参数要求是文档ID,而非查询筛选条件。要实现按条件更新文档,必须先执行查询找到匹配的文档,再对其进行更新操作。

修正后的代码

if(myDescription.length < 15){
    alert("The description must be longer !")
    return
}

const currentUID = auth.currentUser.uid

// 1. 构建查询:筛选出uid与当前用户ID匹配的文档
const q = query(collection(db, "descriptions"), where("uid", "==", currentUID))
// 2. 获取查询结果快照
const querySnapshot = await getDocs(q)

// 3. 遍历匹配的文档并更新
querySnapshot.forEach(async (doc) => {
    await updateDoc(doc.ref, {desc: myDescription})
})

// 若确定只会有一个匹配文档,可简化为:
// if (!querySnapshot.empty) {
//     const targetDoc = querySnapshot.docs[0]
//     await updateDoc(targetDoc.ref, {desc: myDescription})
// } else {
//     // 无匹配文档时,可选择创建新文档
//     await addDoc(collection(db, "descriptions"), {uid: currentUID, desc: myDescription})
// }

核心要点

  • doc()仅用于指定已知ID的单个文档,不能直接传入查询条件。
  • 需通过query()定义筛选规则,配合getDocs()获取符合条件的文档快照,再通过doc.ref获取文档引用进行更新。
  • 使用updateDoc()仅更新指定字段,避免覆盖文档中其他已有数据;若需完全替换文档内容,可继续使用setDoc()。
  • 可补充无匹配文档时的逻辑(如创建新文档),提升代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:50:25