Search code examples
firebasevue.jsvuexvuefirevuexfire

Vuexfire {serialize} option not formatting array properly


I am trying to add all Firestore document Ids when I query a collection. I can query all collections in an instance, but cannot tie their document Ids to the collection arrays.

This is the code I have that works to query all a user's products within a vuex file called product.js

import { firestoreAction } from 'vuexfire'
import { db } from '@/firebase/init'

const state = {
  products: []
}

const getters = {}

const actions = {
  init: firestoreAction( context  => {
    const allProducts = db.collection(`users/${context.rootState.authentication.user.uid}/products`)
    context.bindFirestoreRef(
      'products',
      allProducts, { 
        wait: true, 
        serialize: doc => {
          // console.log(doc.id) -returns the IDS I am looking for
          return Object.defineProperty(doc.data(), 'id', {
            value: doc.id
          })
        }
      }
    )
  })
}

I then get this data

[
   {
      "name":"product1"
   },
   {
      "name":"product2"
   }
]

I am looking to get data to pass to vuex like this:

[
   {
      "id":"kmp1Ue8g0I130XZ3Ttqd",
      "name":"ll"
   },
   {
      "id":"qswtcdmnxNxbwmPNR1S3",
      "name":"fdsfs"
   }
]

The above ids show up when I use console.log(doc.id), but I don't get the expected array with id values, just product name


Solution

  • This is because you cannot modify the Object returned by doc.data().

    The following, using the object spread operator to create a new plain object, should do the trick:

    return {
       id: doc.id,
       ...doc.data()
     }