【问题标题】:firebase/firestore: create and store unique id for documents (users for USERID)firebase/firestore:为文档创建和存储唯一 ID(用户为 USERID)
【发布时间】:2018-07-07 18:08:08
【问题描述】:

我想根据位置为每个用户生成唯一 ID。例如:如果用户来自 newyouk,则 ID 为 NY-23234。这应该在用户第一次注册我的应用时发生。

我发现我可以使用自动生成的 firestore ID - 但是分配为 id 太长了,而且它不能有任何其他字符。我正在使用 angularfire2 连接到 Firestore。

我现在想的是: 每次注册新用户时,将用户详细信息保存在“用户集合”中(使用 firestore 授权生成的密钥作为文档密钥)并运行 firebase 函数以在“用户”集合中创建项目。它应该从同一位置返回最后一个 singup 用户 ID 并添加“1”。然后将该号码保存给新创建的用户。

有什么建议吗?任何其他方式。

【问题讨论】:

    标签: angular firebase google-cloud-firestore


    【解决方案1】:

    我在我的代码中运行了一个类似的问题。 我需要创建一个随机密钥,所以我找到了this code(由客户端的firestore使用):

      const chars'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let autoId = ''
      for (let i = 0; i < 20; i++) {
        autoId += chars.charAt(Math.floor(Math.random() * chars.length))
      }
    

    检查您的用户是否来自纽约

    If (myUserIsFromNy) {
    let ny = "NY ";
    let res = ny.concat(autoId);
    }
    

    autoId 是 firestore 在 .add() 方法上生成的 id。

    相反,您可以创建自己的函数并将其存储在变量中,

    let key = myKeyFunction()
    

    一个好主意是:

      const chars'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let autoId = ''
      for (let i = 0; i < 5; i++) {
        autoId += chars.charAt(Math.floor(Math.random() * chars.length))
      }
    

    执行一个函数来查找您的用户所在的位置并获取来自城市的前两个字母。 首先,您可以检查

    https://www.w3schools.com/html/html5_geolocation.asp 通过纬度和经度,您可以创建一个函数来查找它的位置、城市等...... 或者您可以通过在注册表格中询问来简化操作。

    然后:

    let ny = "NY-"
    let key = ny.concat(autoId)
    

    您可以使用以下方法创建文档:

    db.ref.doc(key).set(Data)
    

    Data 是您的用户信息

    运行云功能来执行此操作是一个糟糕的解决方案,因为服务器将对每个新用户进行额外的写入,您应该只运行 1 次写入并将运行两次,这将增加使用 firestore 的成本,firestore 会强制您执行最佳实践,因为如果不这样做,您将为此付费。

    【讨论】:

    • 感谢您的回复。不幸的是,我有一段时间没有接触电脑了。我会查看这个解决方案并更新我的回复。谢谢
    • 这是个坏主意。只需这样做:db.ref.doc(db.ref.doc().id).set(Data)
    【解决方案2】:

    如果你使用 angularfire2 你应该使用 createId() 函数:

    //Defination:
    import { AngularFirestore } from 'angularfire2/firestore';
    // in constructor
    export class Foo{ constructor(private afs: AngularFirestore)}
    //then use it:
    const id = this.afs.createId();
    

    注意:我不确定此 ID 是否唯一
    编辑
    在 Firestore 中,每个文档都有唯一的 ID。你可以用它。例如,您可以通过创建这样的文档来添加额外的字段:

    this.afs.collection('collection_name').add(your_obj)
    .then(ref => {
    ref.set({ extra_idField: ref.id }, { merge: true }).then(() => {
    console.log("Your extra id field has been created");
    });
    

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 2020-07-24
      • 2020-11-16
      • 2019-12-03
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多