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

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.


If using promises, I'd recommend using fat arrow function as it opens up the possibility for using this.foo even in the .then function

    db.collection("cities").add({
        name: "Tokyo",
        country: "Japan"
    })
    .then(docRef => {
        console.log("Document written with ID: ", docRef.id);
        console.log("You can now also access this. as expected: ", this.foo)
    })
    .catch(error => console.error("Error adding document: ", error))

Using function(docRef) means you cannot access this.foo, and error will be thrown

    .then(function(docRef) {
        console.log("Document written with ID: ", docRef.id);
        console.log("You can now NOT access this. as expected: ", this.foo)
    })

While fat arrow functions will allow you to access this.foo as expected

    .then(docRef => {
        console.log("Document written with ID: ", docRef.id);
        console.log("You can now also access this. as expected: ", this.foo)
    })

Edit/addition 2020:

A more popular way these days may be to use async/await instead. Notice that you have to add async in front of the function declaration:

    async function addCity(newCity) {
      const newCityAdded = await db.collection("cities").add(newCity)
      console.log("the new city:", newCityAdded)
      console.log("it's id:", newCityAdded.id)
    }

And if you only want the id it can be grabbed using descructuring. Destructuring allows you to grab any key/value-pair in the response:

    async function addCity(newCity) {
      const { id } = await db.collection("cities").add(newCity)
      console.log("the new city's id:", id)
    }

It's also possible to use destructuring to grab the value and rename to whatever you want:

    async function addCity(newCity) {
      const { id: newCityId } = await db.collection("cities").add(newCity)
      console.log("the new city's id:", newCityId)
    }

If you want to use async/await instead of .then(), you can write it like this:

const post = async (doc) => {
    const doc_ref = await db.collection(my_collection).add(doc)
    return doc_ref.id
}

If you want to catch any errors in this function, include .catch():

    const doc_ref = await db.collection(my_collection).add(doc).catch(err => { ... })

or you can have the calling function catch the error.