Search code examples
vue.jsgoogle-cloud-firestorevuefirevue-tables-2

Getting documents with ID from firstore collection


While using Firestore, vuefire, vue-tables-2, I stuck getting document's id.

My data structure is as below. enter image description here

Here is my code.

  <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')
    },
  };

My expectation is devices should id property as vuefire docs.

But array this.devices didn't have id field even if I check it exist it console.

enter image description here enter image description here


Solution

  • Basically, every document already has id attribute, but it's non-enumerable

    Any document bound by Vuexfire will retain it's id in the database as a non-enumerable, read-only property. This makes it easier to write changes and allows you to only copy the data using the spread operator or Object.assign.

    You can access id directly using device.id. But when passing to vue-tables-2、devices is copied and lost id non-enumerable attribute.

    I think you can workaround using computed property

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

    Then, please try using devicesWithId in vue-tables-2 instead.