【问题标题】:How i can get a random user from my firebase user list?如何从我的 firebase 用户列表中获取随机用户?
【发布时间】:2018-07-21 21:15:27
【问题描述】:

我正在开发一个应用程序,需要从我的 firebase 用户列表中获取一个随机用户。每当用户注册时,系统都会更新特定节点上的用户计数。所以,我画了一个从 1 到总用户的数字。现在,如何根据该数字选择用户?

【问题讨论】:

    标签: javascript firebase


    【解决方案1】:

    假设您的所有用户都存储在 /users 节点中,其中包含他们的 uid 键,并假设 uid 是有序的(它们总是如此),有几个选项。

    1) 将 /users 节点中的所有用户加载到一个数组中,然后通过它的索引选择您想要的用户。假设我们想要第 4 个用户:

    let usersRef = self.ref.child("users")
    usersRef.observeSingleEvent(of: .value, with: { snapshot in
        let allUsersArray = snapshot.children.allObjects
        let thisUserSnap = allUsersArray[3]
        print(thisUserSnap)
    })
    

    虽然这适用于少量用户,但如果您假设 10,000 个用户和每个节点中存储的大量数据,它可能会使设备不堪重负。

    2) 创建一个单独的节点来存储 uid。这是一个小得多的数据集,其工作方式与 1)

    uids
      uid_0: true
      uid_1: true
      uid_2: true
      uid_3: true
      uid_4: true
      uid_5: true
      uid_6: true
      uid_7: true
    

    3) 进一步减小数据集的大小。既然您知道自己有多少用户,请将数据集分成两部分并使用它。

    使用与 2) 相同的结构

    let uidNode = self.ref.child("uids")
    
    let index = 4 //the node we want
    let totalNodeCount = 8 //the total amount of uid's
    let mid = totalNodeCount / 2 //the middle node
    
    if index <= mid { //if the node we want is in the first 1/2 of the list
        print("search first section")
    
        let q = uidNode.queryLimited(toFirst: UInt(index) )
    
        q.observeSingleEvent(of: .value, with: { snapshot in
            let array = snapshot.children.allObjects
            print(array.last) //the object we want will be the last one loaded
        })
    } else {
        print("search second section")
    
        let q = uidNode.queryLimited(toLast: UInt(index) )
    
        q.observeSingleEvent(of: .value, with: { snapshot in
            let array = snapshot.children.allObjects
            print(array.first) //the object we want will be the first one loaded
        })
    }
    

    此方法仅返回列表的 1/2,因此它是更易于管理的数据量。

    【讨论】:

      【解决方案2】:

      如果您谈论的是经过身份验证的用户,检索他们列表的唯一方法是调用相应的 admin function 并在之后对其应用您的逻辑。

      另一种方法是编写trigger for your authentication 并将用户ID 存储为递增数字(并且可能保存一个totalUser 字段),然后您只需要生成一个随机数并访问所述用户。

      【讨论】:

      • 将用户数据存储在 /users 节点中是相当普遍的做法,其中 uid 作为每个用户的密钥(请参阅我的回答),因此会有一些选项来获取经过身份验证的用户数据。第二个建议的问题是,如果用户 3 被删除 - 这将在顺序列表 0、1、2、4、5、6 中留下一个洞,然后如果生成一个随机数,例如 3,它就会中断。这是在 NoSQL 数据库中应避免使用数组的原因之一。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2020-06-22
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多