Firestore - How to get document id after adding a document to a collection

Brejuro picture Brejuro · Feb 12, 2018 · Viewed 45.8k times · Source

Is there a way to acquire the document id that was generated after adding a document to a collection?

If I add a document to a collection that represents a "post" in a social media app, I want to get that document id and use it as a field in another document in a different collection.

If I can't get the document Id that was generated after adding a document, should I just compute a random string and supply the id when creating the document instead? That way I can use that same string as the field in my other document?

Quick structure example:

POST (collection)
    Document Id - randomly generated by firebase or by me
USER (collection)
    Document Id - randomly generated by firebase
       userPost: String (this will be the document id 
                         in the post collection that I'm trying to get)

Answer

Daniel Konovalenko picture Daniel Konovalenko · Feb 12, 2018

Yes it is possible. When you call the .add method on a collection, a DocumentReference object is returned. DocumentReference has the id field, so you can get the id after the document was created.

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

This example is in JavaScript. Visit the documentation for other languages.