1

I have a signup activity where users sign into firebase. But I want each user to have a different username of the format username#4-digit-code. How can I achieve this with Firestore as i found out with this post that we can't use queries in our transactions?

What would be the best approach for it to prevent two users from having the same userid?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
User
  • 79
  • 6

1 Answers1

1

What would be the best approach for it to prevent two users from having the same userid?

The best option that you have is to check if the username#4-digit-code already exists in Firestore. If it doesn't, add it with the corresponding data, otherwise, generate a new one. This operation should continue until you find an user name which is available.

If you want to make sure you aren't doing many checking operations, then you have to make sure you always generate unique user names, or you can use Firebase Authentication, and instead of that username#4-digit-code you can use the UID that comes from the authentication process.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • But if two users try to generate the same id at the same time wouldn't one overwrite the other? – User Oct 29 '21 at 15:16
  • No, an overwrite takes place only if a document **already** exists and you try to set it again, using the same document ID. That's the reason why you should always check that out, before writing something in the database. If you worry about concurrency, you might also consider using transactions, but it might not be the case. – Alex Mamo Oct 29 '21 at 15:28
  • I'm still thinking of using a cloud function. They get invoked in serially right? Like if i created a function to generate `username#4-digit-code` and call it from my application. Then the function won't run in multiple instances right? Because that userid will be stored inside the document of the user with the firebase auth uid so there are chances of two users storing the same userid inside their own documents – User Oct 29 '21 at 20:38
  • I'm not sure how can Cloud Functions help in this case, but I cannot see any chances to have two separate users sharing the same user name, as long as you check that first. – Alex Mamo Oct 30 '21 at 06:50