I've got users like this inside my database:
users
--45jklj4kljfejlk34 // random uid
----id: 1 // I add this manually when creating a user (maybe it helps getting a random user)
----someData: true
--454jkljkljefnd4lk
----id: 2
----someData: true
I want to get a random user, but I don't know how. I tried sth. like this:
let usersCount = DataService.sharedInstance.DB_USER_COUNT
let rand = Double(arc4random_uniform(UInt32(usersCount))) + 1
let userRef = DataService.sharedInstance.DB_REF_USERS.queryOrdered(byChild: "id").queryStarting(atValue: rand).queryLimited(toFirst: 1))
I get usersCount from the database. There, I increment the figure every time I add a user.
But this doesn't work. This is what I get if I printed this:
(/users {
i = id;
l = 1;
sp = 1;
vf = l;
})
Any suggestions, how I can achieve this?
So, as firebase works quite differently than relational based databases, redundancies seem acceptable in order to be fast and efficient. So I came up with a workaround that works for me.
When I create a user I add him to the "users" tree. Additionally, I add him to a "numUsers" tree (I'm terrible at choosing names, sorry for that). This looks like that:
So, "numUsers" consists of an
id
as key and theuid
as value. Every time I add a new user, I grab the "usersCount" (which I incremented by 1 before) and use it as key.This way, I can easily grab a random user by using this: