Is there a way to access the Auto-Generate document ID from Firestore?

Viewed 730

may I know is there any way to access the Auto-Generate document ID in Firestore using Java? Because I want to add new field and data to existing document through my own android app. I have gone through the documentation, but didn't find any that solve the problem.

Elaboration of problem: I try to obtain the auto-generate ID of each "Event" document for the purpose of adding/update new field "Save Event" for each "User" in Firestore. So that 1 user can save many "event" inside the firestore.Code that I try to figure out DB structure

1 Answers

In order to use the document ID that you are looking for, first, you need to store it in a variable. When you are adding a document to the database and you are using a document() method call without passing any arguments, a unique ID is generated. To get that ID, you should use the following code:

String docId = collRef.document().getId();
collRef.document(docId).set(obj);

In which "collRef" is a reference that points to the collection in which you want to add the document, and the "obj" is the object that you want to be added to the database.

If needed, you can also store the document ID, as a property of your object.

Once you have this ID, you can perform the update like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference collRef = rootRef.collection("collName");
collRef.document(docId).update(map).addOnCompleteListener(/* ... /*);
Related