F
F
Figment2019-02-13 00:26:37
firebase
Figment, 2019-02-13 00:26:37

Firestore: how to get the document ID when listening to a collection?

Hello!
Not quite sure how to solve the following problem, namely how to get the auto-generated document ID when listening to a collection? That is, we have the following code:

created() {
    // Get current user and get info from db
    let currentUser = firebase.auth().currentUser
    this.$store.dispatch('setUserId', currentUser.uid)

    let ref = db.collection('categories').where('user_id', '==', currentUser.uid).orderBy('category_name')
    ref.onSnapshot(snapshot => {
      // snapshot.forEach(doc => {
      //   тут у нас есть doc.id
      //   return this.$store.commit('addCategory', {category_name: doc.data().category_name, user_id: doc.data().user_id})
      // })

      snapshot.docChanges().forEach(change => {
        if (change.type == 'added') {
      //   тут какой-либо doc.id или change.id у нас нет
          let doc = change.doc
          return this.$store.commit('addCategory', {category_name: doc.data().category_name, user_id: doc.data().user_id})
        }
      })
    })
  }

The bottom line is that I keep track of the documents in the collection and when a new one appears, I add it to the vuex store. The problem is that using snapshot.docChanges() I can't get to the document ID. I would not really like to create my own, because why, if it is already there.
If we just use snapshot.forEach , then we have a document id parameter. That is, we can get the document ID through doc.id. There is no such thing for docChanges() . You can get to the ID in the parameters, but then the entry looks like "changes.doc._document.key.path.segments[6]" , which doesn't look very cool.
I want to get Id in order to make more correct queries in the database in the future, to delete / edit records. You can do without it, but I would like to figure out how to get it right.
Thank you very much for the answer!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question