【问题标题】:(Firebase Firestore)TypeError: n.indexOf is not a function(Firebase Firestore)TypeError: n.indexOf 不是函数
【发布时间】:2022-06-19 23:47:29
【问题描述】:

我正在尝试在文档中添加另一个字段值,但 firebase 返回 TypeError: n.indexOf is not a function。代码如下:

async function linkLCSN(cor, sn) {
  try {
    await setDoc(doc(db, "cor", cor), {
      sn: sn,
    }, {merge: true});
  } catch(e) {
    console.error(e);
  }
} 

我已经成功地这样做了,但我不知道为什么这次它一直给我这个错误。这是工作代码:

async function submitToDatabase(name, email, cor, cs, cn, concern) {
    try {
        //Set Datas 
        await setDoc(doc(db, "cor", cor), {
        name: name,
        email: email,
        cor: cor,
        courseSection: cs,
        contactNumber: cn,
        isViewed: false,
        timestamp: serverTimestamp(),
        }, {merge: true});
        const docRef = await addDoc(collection(db, "cor", cor, "concerns"), {
        concernData: concern,
        });
        console.log("Yung betlog nasa:" + docRef.id);
        //Do page changes
        let a = document.querySelector(".concern-main-container");
        let b = document.querySelector(".concern-preview-container");
        a.style.display = "none";
        b.style.display = "block";
    } catch(e) {
        console.error(e);
        //Custom Alert
    }
}

【问题讨论】:

  • 这通常意味着您正在调用带有一些非法值的写入函数。您能否将您的问题编辑为:1) 显示 db 的初始化方式,2) 记录 cor 的值并显示更新后的代码及其输出,3) 您收到的错误消息的完整堆栈跟踪?跨度>
  • 感谢您的回复,我已经找到原因,并且是 cor 给出了无效值。
  • 很高兴听到您发现问题 Sandren Troy! ??? --- 这种类型的故障排除总是最好在您在这里发布问题之前进行,因为开发人员在这样做时自己发现问题实际上是很常见的。对于这个和类似的建议,我建议阅读how to create a minimal, complete, verifiable example
  • 我在使用 Firestore v9 时遇到了同样的“TypeError: n.indexOf is not a function”错误,我在尝试解决这个问题时遇到了这个问题。为将来发现此问题的其他人分享一些反馈:我喜欢 Firestore 和 Firebase,但有时很难弄清楚错误消息到底在告诉你什么。在这种情况下,“TypeError: n.indexOf is not a function”表示您的文档引用无效。

标签: javascript firebase google-cloud-firestore


【解决方案1】:

我通过检查传递给doc() 的每种类型的参数来解决我的问题,这些参数不应该是Integer。必须是String

【讨论】:

    【解决方案2】:

    我假设您使用的是 firebase v9(模块化版本)。这听起来可能很愚蠢,但请确保您已初始化您的应用并且您使用的是对集合的有效引用。

    例如:

    import { initializeApp } from 'firebase/app';
    import { getFirestore } from 'firebase/firestore';
    
    const config = {/** your firebase config properties **/};
    
    const app = initializeApp(config);
    const db = getFirestore(app);
    

    然后添加一个新文档,你可以这样做:

    const createDocument = (collectionName, document) => {
        const colRef = collection(db, collectionName);
        return addDoc(colRef, document);
    };
    

    记住addDoc函数返回一个promise,所以一定要处理这个是createDocument

    的调用者

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2019-05-26
      • 2021-06-11
      相关资源
      最近更新 更多