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

如何处理Firestore v9提交聊天消息时出现的Invalid document reference错误

错误原因
  • Firestore 采用集合与文档交替嵌套的层级结构:路径段数为奇数对应集合,路径段数为偶数对应文档
  • 你代码中使用doc()方法获取路径channels/{channelId}/messages,该路径共3段,属于子集合,不符合doc()要求路径段数为偶数的规则,因此触发报错
  • addDoc()方法本身要求传入集合引用作为参数,传入文档引用本身也不符合方法入参要求
修复方案
  1. 将创建messagesRef时使用的doc方法替换为collection方法
  2. 确认已从 Firestore SDK 中导入collection依赖

修正后的完整代码如下:

// 确认导入所需依赖
import { collection, addDoc, serverTimestamp } from "firebase/firestore";

const sendMessage = async (e) => {
    e.preventDefault();
    let input = inputRef.current.value;
    if (input !== "") {
      // 此处doc改为collection,messages是channels下对应文档的子集合
      const messagesRef = collection(db, "channels", channelId, "messages");
      const payload = {
        timestamp: serverTimestamp(),
        message: inputRef.current.value,
        name: user?.displayName,
        photoURL: user?.photo,
        email: user?.email,
      };
      await addDoc(messagesRef, payload);
      // 可选:提交完成后清空输入框
      inputRef.current.value = "";
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:06:01