Is It Possible To Get The ID Before It Was Added?
FirebaseGoogle Cloud-PlatformGoogle Cloud-FirestoreFirebase Problem Overview
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?
Firebase Solutions
Solution 1 - Firebase
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 - Firebase
const db = firebase.firestore();
const ref = db.collection('your_collection_name').doc();
const id = ref.id;
Solution 3 - Firebase
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 - Firebase
Firebase 9
doc(collection(this.afs, 'posts')).id;
Solution 5 - Firebase
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 6 - Firebase
IDK if this helps, but I was wanting to get the id for the document from the Firestore database - that is, data that had already been entered into the console.
I wanted an easy way to access that ID on the fly, so I simply added it to the document object like so:
const querySnapshot = await db.collection("catalog").get();
querySnapshot.forEach(category => {
const categoryData = category.data();
categoryData.id = category.id;
Now, I can access that id
just like I would any other property.
IDK why the id
isn't just part of .data()
in the first place!
Solution 7 - Firebase
Unfortunately, this will not work:
let db = Firestore.firestore()
let documentID = db.collection(“myCollection”).addDocument(data: ["field": 0]).documentID
db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])
It doesn't work because the second statement executes before documentID is finished getting the document's ID. So, you have to wait for documentID to finish loading before you set the next document:
let db = Firestore.firestore()
var documentRef: DocumentReference?
documentRef = db.collection(“myCollection”).addDocument(data: ["field": 0]) { error in
guard error == nil, let documentID = documentRef?.documentID else { return }
db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])
}
It's not the prettiest, but it is the only way to do what you are asking. This code is in Swift 5
.
Solution 8 - Firebase
In dart you can use:
`var itemRef = Firestore.instance.collection("user")
var doc = itemRef.document().documentID; // this is the id
await itemRef.document(doc).setData(data).then((val){
print("document Id ----------------------: $doc");
});`
Solution 9 - Firebase
For node.js runtime
const documentRef = admin.firestore()
.collection("pets")
.doc()
await admin.firestore()
.collection("pets")
.doc(documentRef.id)
.set({ id: documentRef.id })
This will create a new document with random ID, then set the document content to
{ id: new_document_id }
Hope that explains well how this works
Solution 10 - Firebase
To get ID after save on Python:
doc_ref = db.collection('promotions').add(data)
return doc_ref[1].id
Solution 11 - Firebase
We can see in the docs for doc()
method. They will generate new ID and just create new id base on it. Then set new data using set()
method.
try
{
var generatedID = currentRef.doc();
var map = {'id': generatedID.id, 'name': 'New Data'};
currentRef.doc(generatedID.id).set(map);
}
catch(e)
{
print(e);
}
Solution 12 - Firebase
For the new Firebase 9 (January 2022). In my case I am developing a comments section:
const commentsReference = await collection(database, 'yourCollection');
await addDoc(commentsReference, {
...comment,
id: doc(commentsReference).id,
date: firebase.firestore.Timestamp.fromDate(new Date())
});
Wrapping the collection reference (commentsReference
) with the doc()
provides an identifier (id
)
Solution 13 - Firebase
This works for me. I update the document while in the same transaction. I create the document and immediately update the document with the document Id.
let db = Firestore.firestore().collection(“cities”)
var ref: DocumentReference? = nil
ref = db.addDocument(data: [
“Name” : “Los Angeles”,
“State: : “CA”
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
db.document(ref!.documentID).updateData([
“myDocumentId” : "\(ref!.documentID)"
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
}
}
Would be nice to find a cleaner way to do it but until then this works for me.
Solution 14 - Firebase
In Node
var id = db.collection("collection name").doc().id;
Solution 15 - Firebase
You can use a helper method to generate a Firestore-ish ID and than call collection("name").doc(myID).set(dataObj)
instead of collection("name").add(dataObj)
. Firebase will automatically create the document if the ID does not exist.
Helper method:
/**
* generates a string, e.g. used as document ID
* @param {number} len length of random string, default with firebase is 20
* @return {string} a strich such as tyCiv5FpxRexG9JX4wjP
*/
function getDocumentId (len = 20): string {
const list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
let res = "";
for (let i = 0; i < len; i++) {
const rnd = Math.floor(Math.random() * list.length);
res = res + list.charAt(rnd);
}
return res;
}
Usage: const myId = getDocumentId()
.