【问题标题】:Getting documents with ID from firstore collection从 Firestore 集合中获取带有 ID 的文档
【发布时间】:2019-09-17 15:11:45
【问题描述】:

在使用 Firestore、vuefire、vue-tables-2 时,我一直在获取文档的 ID。

我的数据结构如下。

这是我的代码。

  <v-client-table :columns="columns" :data="devices" :options="options" :theme="theme" id="dataTable">


 import { ClientTable, Event } from 'vue-tables-2'
  import { firebase, db } from '../../firebase-configured'

  export default {
    name: 'Devices',
    components: {
      ClientTable,
      Event
    },
    data: function() {
      return {
        devices: [],
        columns: ['model', 'id', 'scanTime', 'isStolen'],
        options: {
          headings: {
            model: 'Model',
            id: 'Serial No',
            scanTime: 'Scan Time',
            isStolen: 'Stolen YN'
          },
          templates: {
            id: function(h, row, index) {
                return index + ':' + row.id  // <<- row.id is undefined
            },
            isStolen: (h, row, index) => {
                return row.isStolen ? 'Y': ''
            }
          },
          pagination: {
            chunk: 5,
            edge: false,
            nav: 'scroll'
          }
        },
        useVuex: false,
        theme: 'bootstrap4',
        template: 'default'
      }
    },
    firestore: {
        devices: db.collection('devices')
    },
  };

我的期望是设备应该id 属性为vuefire docs

但数组this.devices 没有id 字段,即使我检查它是否存在于控制台。

【问题讨论】:

    标签: vue.js google-cloud-firestore vuefire vue-tables-2


    【解决方案1】:

    基本上,每个文档都已经有id 属性,但它是non-enumerable

    任何被 Vuexfire 绑定的文档都会在数据库中保留它的 id 为 不可枚举的只读属性。这使编写更容易 更改并允许您仅使用扩展运算符复制数据 或 Object.assign。

    您可以使用device.id 直接访问id。但是当传递给vue-tables-2时,devices被复制并丢失了id的不可枚举属性。

    我认为您可以使用computed 属性解决问题

    computed: {
      devicesWithId() {
        if (!this.devices) {
          return []
        }
        return this.devices.map(device => {
          ...device,
          id: device.id
        })
      }
    }
    

    那么,请尝试在 vue-tables-2 中使用 devicesWithId

    【讨论】:

    • 感谢您的回答。你能告诉我如何通过新的deviceWithId。 ` return this.devices.map(device => { let newDevice = {}; newDevice = Object.assign({}, device); newDevice.id = device.id; newDevices.push(newDevice)}`。我检查了设备.id 有它的文档 ID。但卡在通过这些。
    猜你喜欢
    • 1970-01-01
    • 2018-04-04
    • 2021-12-16
    • 1970-01-01
    • 2019-09-24
    • 2020-12-27
    • 2021-07-17
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多