How does String id = db.collection("myCollection").document().getId() gives document Id without hitting Firestore database? - firebase

I read somewhere that db.collection("mycollection").document().getId(); gives document Id in mycollection without hitting cloudstore database. But how it is possible to create unique Id without knowing document id of already existing doucments or hitting couldstore?

The auto-ID that is generated when you call document() is a fairly basic UUID (universally unique identifier). Such identifier are statistically guaranteed to be unique. In my words: there is so much random information in there, that the chances of two calls generating the same value are infinitesimally small.
So Firestore doesn't actually call the server to check whether the ID it generates is unique. It instead relies on the mathematical properties of picking a single value out of a sufficiently large and random set to be very certain it is unique.

Related

Firebase firestore unique values in multiple fields

I'm creating an application for generating documents with unique id, my issue is that the id needs to be in a specific format ( 00000/A/B) so I can't use firestore document's id's.
The problem is also that I have that id's in different places,
#1 case
users/{userID}/id = //UNIQUE ID HERE
#2 case
users/{userID}/members <= members is an array of objects where every member need a unique id
I was thinking about the separate collection of id's where I can check which one is taken but maybe is there a better way to ensure id is unique across the whole app?
What you're considering is pretty much the only way to guarantee uniqueness of a value across the database.
In a few more structured steps, it'd be:
Use that value as the document ID in an secondary collection. This collection purely exists to ensure uniqueness of the IDs.
Let the user claim it, typically by writing their UID into the document.
Use security rules to ensure a user can only write a document if it doesn't exist yet, and (if needed) only deleted when they own it.
The topic of unique values has been covered quite a few times before, although usually in the form of unique user names, so I recommend checking out:
Cloud Firestore: Enforcing Unique User Names
How to generate and guarantee unique values in firestore collection?
How to enforce Uniqueness in a Property of a document field in Google Cloud Firestore
Firestore unique index or unique constraint?
I want to make unique usernames in firebase/firestore

Firebase - Generate a user see-able unique account/document number

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.
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.

Firebase push() and the main thread

I am confused about the functionality of push() in Firebase, even after reading the docs. They present the following code:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Does push() conduct a server query to get a unique ID (thus lagging the main thread--which seems not smart), or does it simply create a "dirty" unique ID that is later checked for uniqueness against the master ledger in the server? The docs seem kind of unclear about the robustness of the ID so I want to make sure.
Firebase's push() method is a pure client-side method. It generates a key based on the current time (corrected for the last known offset of the local clock from the server) and a lot of random information. The key it generates is statistically guaranteed to be unique.
To learn more about these keys, see this blog post: The 2^120 Ways to Ensure Unique Identifiers.

Does the path matter for push ids?

I've been creating a consumer who "grants" ids to clients when they perform certain tasks. It occurred to me at some point that it might be entirely superfluous to worry about the path before I do a .push().name() to create new ids.
Does it matter what path I run the .push().name() on to create a unique ID? Does Firebase generate the IDs entirely based on timestamp, without regard to the path the ID will be assigned to?
Currently, push() ids are generated based on timestamps (along with some randomness). The path on which the id is being pushed is not used as part of the id.

how to generate unique id per user?

I have a webpage Default.aspx which generate the id for each new user after that the id will be subbmitted to database on button click on Default.aspx...
if onother user is also entering the same time the id will be the same ... till they press button on default.aspx
How to get rid of this issue...so that ... each user will be alloted the unique id ...
i m using the read write code to generate unique id ..
You could use a Guid as ids. And to generate an unique id:
Guid id = Guid.NewGuid();
Another possibility is to use an automatically incremented primary column in the database so that it is the database that generates the unique identifiers.
Three options
Use a GUID: Guid.NewGuid() will generate unique GUIDs. GUIDs are, of course, much longer than an integer.
Use intelocked operations to increment a shared counter. Interlocked.Increment is thread safe. This will only work if all the requests happen in the same AppDomain: either process cycling on a refresh of the code will create a new AppDomain and restart the count.
Use an IDENTITY column in the database. The database is designed to handle this, within the request that inserts the new row, use SCOPE_IDENTITY to select the value of the identity to update in memory data (ORMs should handle this for you). (This is SQL Server, other databases have equivalent functionality.)
Of there #3 is almost certainly best.
You could generate a Guid:
Guid.NewGuid()
Or you could let the database generate it for you upon insert. One way to do this is via a Sequence. See the wikipedia article for Surrogate Keys
From the article:
A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.
The Sequence/auto-incremented column option is going to be simpler, and easier to remember when manually querying your DB (during debugging), but the DBA at my work says he's gotten 20% increases in performance by switching to Guids. He was using Oracle, and his database was huge, though :)
I use a utility static method to generate id's, basically use the full datetime(including seconds) and generate a random number of say 3 or 4 characters and return the whole thing, then you can save it to the database.

Resources