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

Firestore添加文件夹时触发‘Function collection() cannot be called with an empty path’错误求助

Firestore添加文件夹时触发‘Function collection() cannot be called with an empty path’错误求助

嘿,我看了你遇到的问题,这个错误其实是因为你在调用addDoc的时候多套了一层collection()函数导致的,咱们一步步理清楚:

错误根源分析

你在firebase.js里已经把database.folders定义成了Firestore的集合引用:

folders: collection(db, 'folders'),

但在AddFolderButton.js的handleSubmit里,你又把这个已有的集合引用传给了collection()函数:

const folderRef = await addDoc(collection(database.folders), { ... })

collection()函数的正确用法是传入Firestore实例和集合路径字符串(比如collection(db, 'folders')),而你传入的是一个已经创建好的集合引用,这就导致它无法解析出有效的路径,所以抛出了“不能用空路径调用collection()”的错误。

修复代码

只需要把collection(database.folders)改成直接用database.folders就行,修改后的handleSubmit函数:

async function handleSubmit(e) {
  e.preventDefault();
  try {
    console.log("Database folders:", database.folders);
    // 直接使用已定义的集合引用,不再套collection()
    const folderRef = await addDoc(database.folders, {
      name: name,
      userId: currentUser.uid,
      createdAt: database.getCurrentTimestamp(),
    });
    console.log(folderRef.id);
    setName("");
    closeModal();
  } catch (error) {
    console.error("Error adding folder to Firestore:", error.message);
  }
}

额外小提醒

我还注意到你firebase.js里的getCurrentTimestamp定义有点问题:

getCurrentTimestamp: serverTimestamp(),

这里你直接调用了serverTimestamp(),这会在初始化firebase配置的时候就生成一个时间戳,而不是在写入数据的时候动态生成。正确的写法应该是把函数本身赋值过去,不要加括号:

getCurrentTimestamp: serverTimestamp,

这样在写入数据时,Firestore才会自动生成服务器端的当前时间戳。

备注:内容来源于stack exchange,提问作者Garvit Gaur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 08:43:01