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

后端 未结 6 1624

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\"

6条回答
  •  情深已故
    2020-12-08 04:54

    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)
    }
    

提交回复
热议问题