1

I am trying to query random user documents from Firebase Firestore.

I use the Firebase Auth UID as id's in Firestore, so instead of a 20-character UID my id's for the user's are the 28-character UID's from Auth.

To get a random document, I want to do the following:

const randomId = firestore.collection.doc().id

// ... all the query logic 

.where(firebase.firestore.FieldPath.documentId(),'>',randomId)

I repeat this process if nothing is found. (like mentioned here).

This would work all great if I had a randomly generated Firebase ID, however since I have Firebase Auth ID's (which are longer), that process does not really work and some documents are never showed.

So I thought I could automatically generate a Firebase Auth UID, but that does not seem to work.

Something like this would be handy:

const randomId = firebase.auth().generateRandomUid()

So my questions:

  1. Is there a way to automatically generate a Firebase Auth UID without actually creating a user?
  2. Is there a better way to query random documents from Firestore with UID as id?

Changing ID's is not an option, and I would like to avoid generating a separate field for that.

Pascal
  • 1,661
  • 17
  • 29

2 Answers2

0

Is there a way to automatically generate a Firebase Auth UID without actually creating a user?

No, there is not. The Firebase Auth UID is generated once the authentication process ends successfully. With other words, once the Firebase user object is created successfully, you get that UID. So you cannot get the Firebase Auth UID without creating an user.

Is there a better way to query random documents from Firestore with UID as id?

If you don't want to use the Firebase Auth UID, you can use the random key that is generated when calling the doc() function. This is more convenient to be used in case you are adding documents in other collections rather than the users collection.

There is also another uid that can be generated but is coming again as a result of an authentication process. So you can check Authenticate with Firebase Anonymously Using JavaScript.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hi Pascal! Can I help you with other informations? If you think that my answer helped you, please consider accepting it. I'd appreciate it. – Alex Mamo Dec 03 '18 at 08:03
0

When you create the user document, add a field called randomSeed or something similar.

In this field you will add the unique ID that you choose how to generate. Now when you want to get a random user, use that field as you explained in your question

// ... all the query logic 

.where('randomSeed,'>',randomId)
TSR
  • 17,242
  • 27
  • 93
  • 197