繁体   English   中英

如何将 user.uid 作为 id 的文档添加到 Firebase 中的集合中?

[英]How to add a document with user.uid as id to a collection in Firebase?

用户第一次使用 Google Auth 提供程序登录时,我想将一个带有user.uid作为 id 的document添加到 "Users" collection中。

如果我使用setDoc添加document

  await setDoc(doc(db, "UsersData", user.uid), {
    username: "",
    isAdmin: false,
    user: JSON.parse(JSON.stringify(user))
  });

并且用户更改了用户名,使用updateDoc完成,这个☝️属性将在每次用户登录时与旧的属性合并。

我试过addDoc

  await addDoc(collection(db, "UsersData", user.uid), {
    username: "",
    isAdmin: false,
    user: JSON.parse(JSON.stringify(user))
  });

但我收到此错误Document references must have an even number of segments UserData... has 3 ,我该如何解决这个问题?

Function addDoc()用于添加具有自动生成 ID 的新文档。 这个 function 只有两个变量,你可以传入集合引用和数据。 有两种方法可以更新文档。 使用updateDoc()setDoc()

使用setDoc() function 将创建一个新文件,如果它不存在并且如果它有选项合并为真则更新。

const docRef = doc(db, 'userData', user.uid)
const result = await setDoc(docRef, { name: user.displayName}, { merge: true })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM