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

如何在React中为Firebase的users集合设置自定义文档ID

自定义Firebase用户集合的文档ID

你的代码当前使用addDoc方法向Firebase的users集合写入数据,这个方法会自动生成随机文档ID。要设置自定义文档ID(比如用用户邮箱作为ID),只需要把addDoc替换为setDoc + doc的组合即可,具体修改如下:

修改后的完整代码

try {
  // 用用户邮箱作为自定义文档ID,先指定文档引用
  const docRef = doc(db, "users", authUser.user.email);
  // 通过setDoc写入数据
  await setDoc(docRef, {
    owner_uid: authUser.user.uid,
    username: username,
    email: authUser.user.email,
    profile_pic: await randomProfiles()
  });
  console.log("CREATED");
  this.props.phase(0);
} catch (e) {
  console.log(e);
} catch (error) {
  console.log(error);
};

修改说明

  • 原代码里addDoc(collection(db, "users"), data)的逻辑是:先获取集合引用,再自动生成文档ID并写入数据
  • 修改后先通过doc(db, "users", authUser.user.email)创建指定了ID的文档引用(这里用用户邮箱当ID,你也可以换成用户UID等其他自定义值)
  • 再用setDoc方法向这个指定的文档写入数据,就能实现自定义ID的需求

内容的提问来源于stack exchange,提问作者MoeezMahmood Ramay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:50:33