簡體   English   中英

Firebase 和 JavaScript。 創建用戶時添加自定義用戶字段

[英]Firebase and JavaScript. Adding custom user fields when creating user

編輯:這是用 Nextjs 制作的。 我創建了一個新的香草 CRA。 它在那里就像一個魅力。 似乎這個問題在某種程度上與 Nextjs 有關。

當創建新用戶時,我正在嘗試創建一個包含其他用戶信息的新用戶文檔。 我有一個 function 它將首先創建一個新用戶,然后在我的用戶集合中填充一個新文檔。

用戶已創建,但用戶集合不會填充包含附加信息的新用戶文檔。

const createUser = (user) => {

  fire.auth()
    .createUserWithEmailAndPassword(user.email, user.password)
    .then((registeredUser) => {
      // shows me the newly created user's id.
      console.log(registeredUser.user.uid);
      fire.firestore().collection('users')
        .add({
          uid: registeredUser.user.uid,
          firstName: user.firstName,
          lastName: user.lastName,
        }).catch((err) => {
          // No errors.
          console.log(err);
        });
    });
};

但是,如果我這樣做,我會在其中添加fire.firestore().collection('users').add({});

我將獲得兩個存儲在用戶集合中的新文檔,一個是來自“dummy”行的空 object,另一個是包含附加用戶信息的文檔。

const createUser = (user) => {
  // If I'm adding this line, I get both the empty object, and the additional user info
  // stored in db.
  fire.firestore().collection('users').add({});

  fire.auth()
    .createUserWithEmailAndPassword(user.email, user.password)
    .then((registeredUser) => {
      // shows me the newly created user's id.
      console.log(registeredUser.user.uid);
      fire.firestore().collection('users')
        .add({
          uid: registeredUser.user.uid,
          firstName: user.firstName,
          lastName: user.lastName,
        }).catch((err) => {
          // No errors.
          console.log(err);
        });
    });
};

有人可以向我解釋為什么會這樣嗎? 為什么第一個代碼塊不起作用? 如何使第一個代碼塊工作,以便在數據庫中獲取我的其他用戶字段?

任何幫助將非常感激。

問候斯蒂芬·瓦盧瓦

完全不清楚為什么需要這一行來添加一個空文檔:

fire.firestore().collection('users').add({});

我會刪除它。 它似乎沒有增加任何價值。

另外,我強烈建議您使用用戶的 UID 作為文檔的 ID,而不是接受 add() 創建的隨機 ID。 僅給定用戶的 UID,這將使您將來更容易定位文檔:

fire.firestore().collection('users').doc(registeredUser.user.uid).set({
    uid: registeredUser.user.uid,
    firstName: user.firstName,
    lastName: user.lastName,
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM