Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework.

We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document.

For instance, within our 'people' collection, we have documents that sometimes contain arrays. Unfortunately, Firebase doesn't seem to support mapping values like an address (e.g., Address: 123 Test street); instead, it only supports array elements such as strings or numbers.

While I did find the arrayRemove methods in the documentation, there seems to be limited information available for other operations.

The snippet below shows a function I'm importing which effectively deletes an item. However, my primary concern now is how to update one.

import { ref } from 'vue'
import { projectFirestore } from '../firebase/config'
import { doc, updateDoc, arrayRemove } from "firebase/firestore";

const useDocumentArray = (firebaseCollection, id, arrayItem) => {
    let error = ref(null)
    let isPending = ref(false)

    let docRef = doc(projectFirestore, firebaseCollection, id);

    const deleteArrayItem = async () => {
        try {
            const res = await updateDoc(docRef, {
                shifts: arrayRemove(arrayItem),
            });
            isPending.value = false;
            return res;
        } catch (err) {
            isPending.value = false;
            console.log(err.message);
            error.value = 'could not delete doc';
        }
    };

    return { error, isPending, deleteArrayItem };
};

export default useDocumentArray;

Answer №1

Is it possible to add, edit, and remove elements in a Firebase cloud document?

Absolutely, Firebase provides functions for each of these operations. You can add a document, modify, or delete a document.

For instance, if we have a collection named people with documents containing arrays, it's worth noting that Firebase does not support key-value mappings like Address: 123 Test Street. Instead, it only supports array elements such as strings or numbers.

Firestore handles fields of type string along with arrays. Make sure to review the supported data types. Additionally, Firestore documents can include objects, providing flexibility for more complex data structures beyond simple arrays.

I came across the arrayRemove method in the documentation, but not much else.

Indeed, using the arrayRemove function allows you to eliminate specific elements from an array. Alternatively, there is an arrayUnion feature available that enables you to append new elements to the 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

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Is there a method in Vue.js to automatically utilize @submit.prevent on all forms within a project?

It has come to my attention that I find myself frequently repeating certain snippets, sometimes even forgetting them. One of these recurring snippets is @submit.prevent. I always include this in all forms to prevent automatic submission, as I prefer handl ...

What is the process for converting a UTC datetime string into the local timezone of users?

I am utilizing Laravel 5.7 for the API and Vue for the frontend development. The API response includes a user's last seen timestamp in UTC format by default, like this: last_seen: "2019-04-17 05:20:37". Laravel API code: $user_details = array( ...

Issue with Refreshing Header Row Filter Control in Bootstrap Table

Currently in the process of developing an application that utilizes Bootstrap Table and its extension, Filter Control. One feature I've incorporated is individual search fields for each column to enhance user experience. The challenge I'm facing ...

The issue with GatsbyJS and Contentful: encountering undefined data

Within the layout folder of my project, I have a Header component that includes a query to fetch some data. However, when I attempt to log this.props.data in the console, all I get is 'undefined'. Could someone please point out where I might be m ...

Using Vue router to bind a class to links and highlight the active class

I am currently working on a project where I need to render a sidebar with links to different pages. The challenge I'm facing is that these sidebar items should have different styles when they are active. Unfortunately, I am unsure of how to create a b ...

AngularJS: Issue with Variable Value Rendering

I recently started working with Angular. In my JavaScript file, I have the following code: App.controller('ProductController', ['$scope', 'ProductService', function ($scope, ProductService) { console.clear(); console. ...

Single array returned by observable

Issue: I am looking for a way to consolidate the multiple arrays returned individually into a single array. Solution: fetchAllRiders() { var distanceObs = Observable.create(observer => { this.http.get(this.API + '/driver/all').map(res = ...

Design a background image that is optimized for both high-resolution retina displays and standard non-ret

Scenario I am working on a web page where I want the background image to be fixed, covering the entire screen or window (excluding tablets and smartphones). The background image has been created using ImageShack. Everything is running smoothly so far. T ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

Conducting various calculations and showcasing them all on a single webpage

Uncertain about what to name this, but let's see if you understand my question. I have a table on a standard HTML page and I am performing some calculations using Javascript/jQuery. Example: function addThem() { var result; result = userIn ...

Protractor is unable to interact with the embedded <span> within the <a> tag

I am facing an issue where I have two nested <span> elements inside an <a> tag. My objective is to trigger a click event on the second <span>. I tried using the by.id method on the custom classes I created, but it did not work. I also att ...

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

Is it possible to use velocity js to add a gradient color effect to text content?

Can I use velocity js to apply gradient color to text? I've looked at https://css-tricks.com/snippets/css/gradient-text/ My specific need is to dynamically add a changing gradient using js. Thank you in advance. ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...