What is the recommended practice for generating unique IDs in Firebase?

Viewed 2067

In SQL Server, we have the NEW_ID() function whenever we want to generate a unique ID. Sometimes, when it's difficult to assign a primary key(s), I use this to uniquely identify a row.

I'm now writing a kotlin android app where I need to store user info in a collection -> document. What is the recommended practice for generating unique IDs for each user? Should I use a simple incrementing value starting with 1?

2 Answers

Firestore does not implement auto increment IDs for documents. Implementing it yourself will incur a performance penalty - that simply does not scale the way the Firestore requires.

If you are adding new documents to a collection, and they don't already have natural IDs, the SDK will generate a random ID for you when you use the add() method on a CollectionReference. This is the preferred way to add new documents, and is covered in the documentation.

If you need ordering of those documents, you should add a field that you can use to order the query. If you want time-based ordering, you should add a timestamp field with the current time.

If you're authenticating user then i would recommend to go with the UID generated by firebase itself. You can refer this for fetching UID for current user.

Else you can generate Unique ID just like we are using push() while using realtime database.

DocumentReference key;
key = db.collection("YOUR_COLLECTION_NAME").document();
UniqueID = key.getId();

Now you can use this UniqueID as document.

Related