简体   繁体   English

Vuexfire {serialize} 选项未正确格式化数组

[英]Vuexfire {serialize} option not formatting array properly

I am trying to add all Firestore document Ids when I query a collection.我试图在查询集合时添加所有 Firestore 文档 ID。 I can query all collections in an instance, but cannot tie their document Ids to the collection arrays.我可以查询一个实例中的所有集合,但不能将它们的文档 Id 绑定到集合数组。

This is the code I have that works to query all a user's products within a vuex file called product.js这是我的代码,用于在名为 product.js 的 vuex 文件中查询所有用户的产品

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:我希望像这样将数据传递给 vuex:

[
   {
      "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当我使用console.log(doc.id)时会显示上面的 id,但是我没有得到带有id值的预期数组,只是产品名称

This is because you cannot modify the Object returned by doc.data() .这是因为您无法修改doc.data()返回的 Object。

The following, using the object spread operator to create a new plain object, should do the trick:下面,使用对象扩展运算符创建一个新的普通对象,应该可以解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM