What caused Firestore to be interpreted as an Array in my program instead of a Collection Reference?

After developing a simple app on Vue, I wanted to add functionality by connecting it to an online database. With limited backend knowledge, I decided to give Firebase a try for its simplicity and speed.

The issue arises when I attempt to retrieve data from the database using Firestore:

firestore () {
      return {
        items: db.collection('items')
      }
    }

However, when I fetch the data, my original array 'items' in the component's 'data()' method gets filled with entire objects from the collection. I only want specific fields like the 'name' field of each to-do item, not the complete object itself. Unfortunately, there seems to be no direct way to access individual fields like 'db.collection('items').name'.

To address this, I considered creating a function to extract the necessary data into an array before passing it to 'items':

function cleanRawData(objectToClean){
      var cleanedArr = [];

      for(let i=0; i<objectToClean.length; i++){
        cleanedArr.push(objectToClean[i].name)
      }

      return cleanedArr
}

 data () {
      return {
          
          items: [],

        }
    },
    firestore () {
      let itemObject = db.collection('items');
      return {
       items: cleanRawData(itemObject)
      }
    }

Although unsure if my approach contains errors, the main goal is to filter the data retrieved from Firestore.

The challenge lies in testing the function as 'console.log(db.collection('items'))' does not provide an array of objects but rather a "Firestore Collection". Strangely enough, the app renders the data seamlessly as if it were a regular array.

Answer №1

If you are utilizing Vuefire and specifically implementing the declarative binding, then with a simple code snippet like:

  firestore: {
    items: db.collection('items')
  }

You are able to populate the items array, which automatically gets updated whenever there is a change in the collection.


Depending on your specific requirement, you can choose one of the two presented approaches below:

<template>
  <div>
    <ol>
      <li v-for="i in items">{{ i.name }}</li>
    </ol>

    <ol>
      <li v-for="n in names">{{ n }}</li>
    </ol>
  </div>
</template>

<script>
import { db } from "../firebase";
export default {
  data() {
    return {
      items: []
    };
  },

  firestore: {
    items: db.collection('items')
  },
  computed: {
    names() {
      return this.items.map(item => {
        return item.name;
      });
    }
  }
};
</script>

If your goal is to simply display the name of each item, you can utilize the first approach with the initial v-for loop. This will display the name property of each item.

However, if you need to create another array containing only the names, consider using a computed property. The second v-for demonstrates the same result by iterating over the names (computed) array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

Dealing with loading issues in ChartJS due to Axios API integration in a Vue.js project

Struggling to display charts for a Vue.JS dashboard with a flask API acting as a dummy backend. Currently following the guide on but facing difficulties in visualizing data. Component code: <template> <Bar v-if="loaded" :dat ...

Switch between two distinct menus (Reactjs + Material UI)

Recently, I designed a robust menu system that includes a Switcher feature. The concept is straightforward - if the switch is turned off, display the 1st menu; and if it's on, show the second menu. However, there seems to be an issue. When the switch ...

How can I convert string-based data to numerical values within an API response object using JavaScript?

Currently, I am utilizing the Alpha Vantage API through RAPID API. The response object schema from the API appears as shown in the link below: https://i.sstatic.net/FEm0u.png To visualize this data on a chart, I need to remove the quotation marks surroun ...

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

Working through JSON arrays in JavaScript

Here is a JSON example: var user = {"id": "1", "name": "Emily"} If I select "Emily," how can I retrieve the value "1"? I attempted the following code snippet: for (key in user) { if (user.hasOwnProperty(key)) { console.log(key + " = " + use ...

Each time the page is refreshed, the most recent form data submitted is continually appended to an array

I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form ...

"By setting the HTML input box to read-only, the JavaScript button has the

Check out this js fiddle demonstration: http://jsfiddle.net/YD6PL/110/ Here is the HTML code snippet: <input type="text" value="a" readonly> <input type="text"> <input type="text"> <div> <button class="buttons">c</button ...

Adjust the x-axis on the Vue.js bar chart

I'm currently working on a Vue.js Laravel application where I am trying to incorporate a bar chart using the ApexCharts module. <apexchart ref="apexChart" :options="chartOptions" :series="chartData" type="bar" ...

What could be causing the error message "SyntaxError: illegal character" to appear?

When I try to use the following code: var colorsone = ["#F0F8FF", "#FAEBD7", "#00FFFF", #7FFFD4", #F0FFFF","#F5F5DC", "#FFE4C4", "#000000", "#FFEBCD", "#0000FF", "#8A2BE2", "#A52A2A", "#DEB887", "#5F9EA0", "#7FFF00", "#D2691E", "#FF7F50", "#6495ED", "#FFF ...

Issue with Telerik RadDatePicker when using ClientIDMode set to "Static"

var StartDate = $('#dtStartDate').val(); var EndDate = $('#dtEndDate').val(); alert(StartDate); alert(EndDate); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table> <tr ...

Having trouble loading the React app when using the @mui/styles package

After downloading a package from the MUI website, I encountered an error when trying to import "@mui/styles" which is resulting in browser errors. The package was downloaded from this source: https://mui.com/system/styles/basics/ Upon running my React app ...

Is it optimal to count negative indexes in JavaScript arrays towards the total array length?

When working in JavaScript, I typically define an array like this: var arr = [1,2,3]; It's also possible to do something like: arr[-1] = 4; However, if I were to then set arr to undefined using: arr = undefined; I lose reference to the value at ...

Avoiding triggering the parent event from the child in React

I'm facing a situation where clicking on a parent element results in it flipping to display a child element with different colors. However, the issue arises when the user tries to click on one of the colors in the child element, as it also triggers th ...

generate iframes on secure websites

I'm in the process of developing a bookmarklet. Essentially, it retrieves a snippet of JavaScript code from the server and generates an iframe on websites with different domains. While it operates smoothly on http websites, it appears to be restricte ...

Transform a set of numerical values in a JavaScript array into indexed pairs

Let's say I have an array of numbers presented in this format: [5, 29, 1, 5, 4919, 109, 17] My goal is to transform this array into pairs of numbers based on their index within the array. The desired output would look like this: [[0, 5], [1, 29], [ ...

Increase the character count when two spans contain data

I am currently working with the code provided below. The user interface allows users to choose either a single date or a range of dates. These dates are displayed within span tags, with a "-" symbol intended to be shown if there is a valid toDate. However, ...

Guide to encapsulating an angular material form within a component and making it accessible to the FormGroup as a formControl property

My goal is to create a custom component (let's call it custom-input) that acts as a formControl element using Angular material components. It should include the following structure: <mat-form-field > <input matInput [formControl]=" ...

"Is there a function for the event emitter in Node.js using ES6

I'm currently in the process of developing a class in which every instance can react to an event: const events = require("events"); const eventEmitter = new events.EventEmitter(); class Camera { constructor(ip) { this.ip = ip; } ...

Is there a way to disable default tooltips from appearing when hovering over SVG elements?

Looking for a way to display an interactive SVG image on an HTML page without default tooltips interfering. While I'm not well-versed in javascript/jQuery, I've managed to implement customized tooltips using PowerTip plugin. However, these custom ...