每个用户的Firebase文档? [英] Firebase Document for each user?

查看:103
本文介绍了每个用户的Firebase文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering how to make a document for each user as they create their account (with Firebase Web). I have Firebase Authentication enabled and working, and I'd like each user then to have a document in Cloud Firestore in a collection named users. How would I get the UID and then automatically create a document for each user? (I am doing this so that calendar events can be saved into an array field in the document, but I need a document for the user to start with). I am aware and know how to make security rules for access, I just don't know how to make the document in the first place. Thanks!

推荐答案

尽管绝对可以通过Cloud Functions创建用户个人资料文档(正如Renaud和guillefd所建议的那样),但也可以考虑直接从应用程序代码中创建文档.该方法非常相似,例如如果您使用的是电子邮件+密码登录:

While it is definitely possible to create a user profile document through Cloud Functions, as Renaud and guillefd suggest, also consider creating the document directly from your application code. The approach is fairly similar, e.g. if you're using email+password sign-in:

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;
    // ...
  });

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

Aside from running directly from the web app, this code also creates the document with the user's UID as the key, which makes subsequent lookups a bit simpler.

这篇关于每个用户的Firebase文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆