如何处理Firestore v9提交聊天消息时出现的Invalid document reference错误
错误原因
- Firestore 采用集合与文档交替嵌套的层级结构:路径段数为奇数对应集合,路径段数为偶数对应文档
- 你代码中使用
doc()方法获取路径channels/{channelId}/messages,该路径共3段,属于子集合,不符合doc()要求路径段数为偶数的规则,因此触发报错 addDoc()方法本身要求传入集合引用作为参数,传入文档引用本身也不符合方法入参要求
修复方案
- 将创建
messagesRef时使用的doc方法替换为collection方法 - 确认已从 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
相关产品推荐
相关产品推荐

