Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestore

Is It Possible To Get The ID Before It Was Added?


I know that in Realtime Database I could get the push ID before it was added like this:

 DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
 String challengeId=databaseReference.push().getKey();

and then I could add it using this ID.

Can I also get it in the Cloud Firestore?


Solution

  • This is covered in the documentation. See the last paragraph of the add a document section.

    DocumentReference ref = db.collection("my_collection").doc();
    String myId = ref.id;