【问题标题】:Firebase: use email ID as a keyFirebase:使用电子邮件 ID 作为密钥
【发布时间】:2019-04-02 04:53:38
【问题描述】:

在使用 Firebase 读取时间数据库进行建模时,无法确定唯一键。

我的用户集合被标识为电子邮件 ID。
所以我的目标是对数据库进行建模,如下所示。

{
  "users": {
    "aa@dd.com": {
      "name": "aa",
      "addr": "new york",
      "tel": "3224323"
    },
    "bb@dd.com": {
      "name": "bb",
      "addr": "new york",
      "tel": "3224323"
    },
    "cc@dd.com": {
      "name": "bb",
      "addr": "new york",
      "tel": "3224323"
    },
    "dd@dd.com": {
      "name": "cc",
      "addr": "new york",
      "tel": "3224323"
    }
  }
}

但 Firebase 不允许将某些特殊字符作为键。如@:

如何修复我的建模以适应 Firebase?

【问题讨论】:

    标签: firebase firebase-realtime-database database-design


    【解决方案1】:

    您可以从将电子邮件作为唯一密钥更改为使用通过 firebase 身份验证获得的唯一 ID。

    如果您使用UID,那么您将能够在身份验证中相互连接firebase数据库,因为它是由firebase身份验证提供的。此外,如果用户更改了他的电子邮件,那么您需要更改数据库以适应用户的更改。

    检查以下内容:

    https://firebase.google.com/docs/auth/web/manage-users#get_a_users_profile

    【讨论】:

      【解决方案2】:

      实际上,firebase 不允许仅使用“.”、“#”、“$”、“[”或“]”字符...:

      Uncaught (in promise) Error: Reference.child failed: 
      First argument was an invalid path = "firebase/xxx@gmail.com/data". 
      Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
      

      ...所以这种情况下的问题只是'。'字符。

      因此,如果在您的用例中,可以更改 '.'用别的东西你可以做这个规则:

      {
        "rules": {
          "users": {
            "$email": {
                ".read": true,
                ".write": "$email === auth.token.email.replace('.', ',')",                    
            }
          }
        }
      }
      

      (灵感来自:https://firebase.google.com/docs/reference/security/database#replacesubstring_replacement

      从现在开始,只需像这样保存数据:

      const email = firebase.auth().currentUser.email.replace(/\./g, ',');
      // test@gmail,com
      
      await firebase.database()
          .ref(`users/${email}/data`)
          .set({
              name: "eee",
              addr: '56 Barker Close',
              tel: '1234567890'
          });
      

      所以最后数据会是这样的:

      {
        "users": {
          "aa@dd,com": {
            "name": "aa",
            "addr": "new york",
            "tel": "3224323"
          },
          "bb@dd,com": {
            "name": "bb",
            "addr": "new york",
            "tel": "3224323"
          },
          "cc@dd,com": {
            "name": "bb",
            "addr": "new york",
            "tel": "3224323"
          },
          "dd@dd,com": {
            "name": "cc",
            "addr": "new york",
            "tel": "3224323"
          },
          "test@gmail,com": {
            "name": "eee",
            "addr": "56 Barker Close",
            "tel": "1234567890"
          }
        }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-21
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        • 2012-10-06
        • 2012-04-13
        相关资源
        最近更新 更多