每次有人在 firebase 中注册时创建一个文档

Creating a document every time someone signs up in firebase

所以我正在制作一个小的网络应用程序,这是我第一次尝试同时使用 firebase 和 React Js,所以我的问题是每次新用户注册时我都试图在 fireStore 中制作一个文档

// this is my SignUp Function 

  async function signUp(email, password,) {
     await createUserWithEmailAndPassword(auth, email, password);
  }

/*and Im calling in it my component and as onSubmit Function and passing it the email and password 
and this is where things got me a little tricky because wheni tried to pass my CreateDocument Function as a callBack it throws me an error 

and this is my CreateDocument
 function   const creatProfileDocument = (currentuser) => {
    setDoc(doc(db, "users", currentuser.uid), {
      email: currentuser.email,
      age: false,
      name: "",
    })
  };*/ 

我真的希望有人能在这里帮助我

通常有两种方法可以解决此问题 - 立即在您的 signUp 代码中或通过 Firebase Functions 中的身份验证触发器。

在您的注册码中

您可以在异步 signUp 函数之后立即创建文档:

async function signUp(email, password) {
  // This function returns a credential which gives you the user's uid
  // which you could then use to create your document
  const credential = await createUserWithEmailAndPassword(auth, email, password);

  const uid = credential.user.uid

  // Create a new document using the uid as the document id
  // or however else you want to use this
  const ref = firebase.auth().collection("users").doc(uid)
  await ref.set({
    email,
    uid
  })
}

这样做的好处是您可以立即创建文档,这样您就可以在 signUp 函数 returns 时知道它就在那里。不利的一面是您必须放宽一些安全规则以允许用户从客户端在此集合上创建文档。有很多方法可以保证它的安全,但请注意这一点。

使用云功能

您的 signUp 代码在 Firebase 中创建了一个新的授权记录,并且 Firebase 有 Authentication trigger functions 可以在创建或删除新的授权记录时触发。

exports.createUserDoc = functions.auth.user().onCreate((user) => {
  // Your new auth record will have the uid and email on it because
  // you used email as the way to create the auth record
  return admin.firestore().collection("users").doc(user.uid).set({
    email: user.email,
    uid: user.uid
  })
});

这是一种安全的处理方式,不需要您开启任何安全规则。但缺点是触发器功能不能保证立即触发。它们通常会在几秒钟内开火,但我见过需要 30-60 秒。因此,如果您的客户端代码需要在创建帐户时立即使用该文档,那么这不是一个可行的选择。