如何在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
相关产品推荐
相关产品推荐

