5

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?

Umid Boltabaev
  • 442
  • 2
  • 6
  • 17
  • Does this answer your question? [Firestore: get document back after adding it / updating it without additional network calls](https://stackoverflow.com/questions/52678252/firestore-get-document-back-after-adding-it-updating-it-without-additional-ne) – zronn May 28 '20 at 15:09
  • Yes, that's right. – Umid Boltabaev May 28 '20 at 15:19

3 Answers3

1

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

Grant Singleton
  • 1,611
  • 6
  • 17
0

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();
}
Umid Boltabaev
  • 442
  • 2
  • 6
  • 17
  • The idea of getting after the add was expressed in @GrantSingleton's answer below. Why not just accept that? Also, I don't see what's being gained by getting and returning the `.data()`. Don't you already have `data = {...}` in the line above? – danh May 28 '20 at 15:25
  • Ah, I see. Sorry. I wish that add would return a server timestamp. I think it is too much to ask for the whole object as written, since triggers running after the add might change it. Anyway, I'm upvoting the essence of the correct answer given first. – danh May 28 '20 at 15:32
0

We could retrieve added or updated data using this function:

function dataToObject(fDoc){
  return { ...fDoc.data(), id: fDoc.id }}

We should chain 'get' method to retrieve added or updated firestore data:

let fDoc = await db.collection("cities").add({
   name: "Tokyo",
   country: "Japan"
}).get()

Use it to transform your snapshot to an object:

const upserData = dataToObject(fDoc)
Zrelli Majdi
  • 1,204
  • 2
  • 11
  • 16