每个用户的 Firebase 文档?

Nee*_*tta 5 javascript firebase google-cloud-firestore

我想知道如何在每个用户创建帐户时为他们制作文档(使用 Firebase Web)。我已启用 Firebase 身份验证并正常工作,然后我希望每个用户在 Cloud Firestore 中名为 users 的集合中有一个文档。我如何获取 UID,然后自动为每个用户创建一个文档?(我这样做是为了将日历事件保存到文档中的数组字段中,但我需要一个文档供用户开始使用)。我知道并知道如何为访问制定安全规则,我只是不知道如何首先制作文档。谢谢!

Fra*_*len 11

虽然正如 Renaud 和 guillefd 所建议的那样,绝对可以通过 Cloud Functions 创建用户配置文件,但也可以考虑直接从您的应用程序代码创建该文档。该方法非常相似,例如,如果您使用电子邮件+密码登录:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(function(user) {
    // get user data from the auth trigger
    const userUid = user.uid; // The UID of the user.
    const email = user.email; // The email of the user.
    const displayName = user.displayName; // The display name of the user.

    // set account  doc  
    const account = {
      useruid: userUid,
      calendarEvents: []
    }
    firebase.firestore().collection('accounts').doc(userUid).set(account); 
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });
Run Code Online (Sandbox Code Playgroud)

除了直接从 Web 应用程序运行之外,此代码还创建了以用户的 UID 为键的文档,这使得后续查找更简单一些。

  • 我想这将需要用户有权在帐户集合中创建文档? (4认同)

gui*_*efd 9

您必须设置一个由onCreate() Auth trigger 触发的 firebase 函数。
1. 创建函数触发器
2. 获取用户创建的数据
3. 设置账户数据。
4. 将账户数据添加到集合中。

函数/index.js

// Firebase function 

exports.createAccountDocument = functions.auth.user().onCreate((user) => {
  // get user data from the auth trigger
  const userUid = user.uid; // The UID of the user.
  //const email = user.email; // The email of the user.
  //const displayName = user.displayName; // The display name of the user.

  // set account  doc  
  const account = {
    useruid: userUid,
    calendarEvents: []
  }
  // write new doc to collection
  return admin.firestore().collection('accounts').add(account); 
});
Run Code Online (Sandbox Code Playgroud)