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 get it also in the Cloud Firestore?
Solution 1:
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;
Solution 2:
const db = firebase.firestore();
const ref = db.collection('your_collection_name').doc();
const id = ref.id;
Solution 3:
You can do this in following manner (code is for AngularFire2 v5, which is similar to any other version of firebase SDK say web, node etc.)
const pushkey = this.afs.createId();
const project = {' pushKey': pushkey, ...data };
this.projectsRef.doc(pushkey).set(project);
projectsRef is firestore collection reference.
data is an object with key, value you want to upload to firestore.
afs is angularfirestore module injected in constructor.
This will generate a new document at Collection called projectsRef, with its id as pushKey and that document will have pushKey property same as id of document.
Remember, set will also delete any existing data
Actually .add() and .doc().set() are the same operations. But with .add() the id is auto generated and with .doc().set() you can provide custom id.
Solution 4:
The simplest and updated (2019) method that is the right answer to the main question:
"Is It Possible To Get The ID Before It Was Added?"
// Generate "locally" a new document in a collection
const document = yourFirestoreDb.collection('collectionName').doc();
// Get the new document Id
const documentUuid = document.id;
// Sets the new document (object that you want to insert) with its uuid as property
const response = await document.set({
...yourObjectToInsert,
uuid: documentUuid
});
Solution 5:
Firebase 9
doc(collection(this.afs, 'posts')).id;