添加用户显示名

时间:2019-01-02 05:02:12

标签: firebase google-cloud-firestore

如何在FireStore中添加DisplayName?我已经读过firebase no displayname for userfirebase user photourl and displaynamethis,但是它们都不起作用,因为它们都引用Firebase而不是Firestore。

2 个答案:

答案 0 :(得分:0)

您可以创建一个云功能来触发帐户创建

functions.auth.user().onCreate(event => {
    const firebaseUser = event.data;

    return firebase.firestore().collection("users").doc(firebaseUser.uid).set({
       name: firebaseUser.displayName || "n/a"
    });
});

这将在由用户的UID标识的名为用户的集合中为该用户创建一个文档。请注意,displayName不一定在auth用户对象中设置。因此,您可能需要设置一个默认的占位符,以后可以查询该占位符,并要求用户为其提供信息。

答案 1 :(得分:0)

var config = {
  apiKey: "REPLACE_WITH_YOUR_FIREBASE_PROJECT_CREDENTIAL",
  authDomain: "REPLACE_WITH_YOUR_FIREBASE_PROJECT_CREDENTIAL",
  databaseURL: "REPLACE_WITH_YOUR_FIREBASE_PROJECT_CREDENTIAL",
  projectId: "REPLACE_WITH_YOUR_FIREBASE_PROJECT_CREDENTIAL",
  storageBucket: "REPLACE_WITH_YOUR_FIREBASE_PROJECT_CREDENTIAL",
  messagingSenderId: "REPLACE_WITH_YOUR_FIREBASE_PROJECT_CREDENTIAL"
};
firebase.initializeApp(config);
// Initialize Cloud Firestore through Firebase
var firestore = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);

firebase.auth().onAuthStateChanged(function(user) {
  //check if user is signed in
  if (user) {
    //user is signed in
    //get user display
    if (user.displayName !== undefined) {
      var username = user.displayName;
      //add displayName to firestore
      firestore
      .collection("users")
      .doc(user.uid)
      .set({
        username: username
      }, {merge: true})
      .then(function() {
        alert('displayName added!');
      })
      .catch(function(e) {
        //there was an error writing to firestore
        //check console
        console.log(e);
      });
    } else {
      //user has not set displayName
      alert('no displayName');
    }
  }
});