0

I want to assign a unique but incremental document/record(a data entry, not Firebase document) number when user generates his/her document in the app.

The document number should be unique integer/long and will be visible on the generated PDF document of the user as Your document number : 1100xxxxxx. This last generate document's number will be stored separately so when a new user generated his/her document, this number can be easily picked, incremented and assigned to user.

This way I won't have to query the database again for the last generated number using sorting as

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("Users")
    .orderBy("DocumentNo", Query.Direction.DESCENDING)
    .limit(1);

Right now, I generate a user by assigning the user.uid to the Firebase document. The reason I want to ensure the uniqueness of generated certificate number is that it will be visible to user and multiple users will be hitting the server at the same time(same millisecond even).

Although, I've seen almost every similar answer but the answer I've found similar to what I was thinking is this. Also, this unanswered question is what I should do but it has problems too.

So, is there a way by which I can generate a unique document/record number to the user? Answer need not be in Flutter, I want the logic mainly.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50

1 Answers1

1

If you want to increment a number every time something happens do:

document.ref.update({unique_value: FieldValue.increment(1)});

That number will be unique. It will work with multiple users hitting the server at the same time.

João Abrantes
  • 4,772
  • 4
  • 35
  • 71
  • Problem is you can't really access the Admin API with Flutter. Hence, I'm looking at Firebase Functions. I can either go for counting the total number of users on user registration and giving it a record id of total number + 1 which then can be used for document number but for a large(10K plus) number of users, it will be very slow and illogical to pull all the data just to get the length of the snapshot. – Lalit Fauzdar Oct 08 '20 at 08:04
  • For which also, I'll have to use Firebase functions. I'm trying to write a function which will pass the total number of users to the app without bringing all the document snapshots. Thank you for the suggestion though. – Lalit Fauzdar Oct 08 '20 at 08:05
  • @LalitFauzdar I have updated the answer with Flutter code. – João Abrantes Oct 08 '20 at 08:43
  • Sorry for being late. But, Thank you, the answer works perfectly. – Lalit Fauzdar Oct 20 '20 at 08:43