How to retrieve added doc data in Firestore?

Viewed 1885

I have such code where I can get new inserted doc 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);
});

Is it possible to get data from ref?

2 Answers

Yes you can do it like this:

.then(function(docRef) {
   db.collection("cities").doc(docRef.id).get()
     .then(snap => {
        console.log('Here is the document you wrote to', snap.data()
      })
})

Granted it requires another read which you probably didn't want

I found solution

static async createUserPofile(uid) {
    const db = Firebase.firestore(),
        date = Firebase.firestore.FieldValue.serverTimestamp(),
        data ={
            user_id: uid,
            creation_time: date,
            update_time: date
        },
        docRef = await db.collection("user_profiles").add(data),
        get = await docRef.get();
    return get.data();
}
Related