Firebase v9 React JS IndexOf 不是一个函数。

4

由于某种原因,控制台会抛出错误 "TypeError: n.indexOf is not a function",我不太理解为什么会发生这种情况。我正在使用Firestore和Firebase v9模块化版本,基本上是一个在Firestore数据库中创建类别,并在类别内创建测试任务的功能。

以下是完整的错误信息:

TypeError: n.indexOf is not a function
    at Function.fromString (index.esm2017.js:1032)
    at va (index.esm2017.js:14990)
    at App.jsx:48

错误信息中的第48行是:

const taskRef = doc(collection(db, "categorias"), where("uid", "==", currentUser), newDocRef.id)

这是我的代码 :)

const currentUser = '1234'

const crearCategoria = useCallback(async() => {
    try {
      const newDocRef = doc(collection(db, "categorias"));

      await setDoc(newDocRef, {
        name: categoryName,
        uid: currentUser,
        projectId: newDocRef.id
      })

      const taskRef = doc(collection(db, "categorias"), where("uid", "==", currentUser), newDocRef.id)
      await setDoc(taskRef, {
       name: 'prueba',
       uid: currentUser,
       projectId: newDocRef.id
    })

    } catch (error) {
      console.log(error)
    }
  })

你想做什么?看起来你正在更新文档,其中("uid", "==", currentUser),这是不可能的。你需要先引用那些文档。 - Dharmaraj
5
我也遇到了Firestore v9中出现的"TypeError: n.indexOf is not a function"错误,当我尝试弄清楚问题时,我看到了这个问题。给那些将来也会发现这个问题的人分享一些反馈:我喜欢Firestore和Firebase,但有时很难弄清楚错误消息在告诉你什么。在这种情况下,"TypeError: n.indexOf is not a function"意味着你有一个无效的文档引用。对于这个特定的例子,修复它的正确方法在Frank的回答中已经提到了,但是更一般地说,如果你看到这个错误,你需要找出为什么你的文档引用是错的。 - most200
-most200。谢谢!这也是我的情况!我意识到我直接引用了用户而不是用户的uid(我的文档名称)。 - Michael Martell
1个回答

4

正如 Dharmaraj 的评论所指出的,您无法对查询执行更新操作。相反,您需要执行以下操作:

  1. 执行查询以查找匹配的文档。
  2. 在应用程序代码中循环遍历文档。
  3. 逐个更新每个文档。

在代码中,应该像这样:

const taskQuery = doc(collection(db, "categorias"), where("uid", "==", currentUser))
const taskDocs = await getDocs(taskQuery)
taskDocs.forEach((taskDoc) => {
  await setDoc(taskDoc.ref, {
    name: 'prueba',
    uid: currentUser,
    projectId: newDocRef.id
  })
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接