1

Whenever a user uses the Firebase Auth to register on my app, I create a document in a users collection of Firestore that stores metadata such as pseudo, userType, gender ...

To do that, the document id is exactly the same as the uid provided automatically by Firebase Auth (from the user UserRecord object)

Now, my app needs to fetch a user randomly from the users collection in Firestore.

I read Firestore: How to get random documents in a collection but this post suggest that I create the ID myself. The app is already built using the FirebaseAuth generated ID so what is the solution ?

TSR
  • 17,242
  • 27
  • 93
  • 197
  • 2
    The approach will be the same as in the answer you linked: generate a random UID value client-side, and then find the closest one to that in the database by ordering by UID, and starting at the random value you generated. – Frank van Puffelen Aug 10 '20 at 14:36
  • @tsr if an answer worked would you kindly mark as the best answer? – Ming the merciless Aug 11 '20 at 16:11

1 Answers1

2

A common practice in firestore is to create a "--Stats--" document within a collection (--Stats-- being the document id). This document can house information about the collection (number of documents, last updated, collection privileges etc.).

In your case, you could use cloud functions/triggers to keep tract of the total number of users in the users collection and add the id of a new user to a "userIds" array. You could keep both of these fields in the users collection's --Stats-- document. This way, when you wanted to get a random user, you could randomly generate a number betweeen 0 and the document count, then use it as an index of the userIds array. I might look something like this:

var usersCollectionRef= db.collection("users");

usersCollectionRef.doc("--Stats--").get().then((doc) => {

    let numberOfUsers = doc.data().numberOfUsers; 
    let userIdArray = doc.data().userIds; 
    let randomNumber = Math.floor(Math.random() * (numberOfUsers + 1));

    return usersCollectionRef.doc(userIdArray[randomNumber]).get();

}).then((doc) => {
   ...do something with the user's document
})