Storing documents with arrays of objects in Firebase Cloud Firestore and Functions

I am facing a challenge where I need to transfer the following JSON data from my local storage to Firebase Firestore:

guides: [  
    {  
       "id":0,
       "name":"name0",
       "sources":[
           {
               "type":"s3",
               "url":"https://s3.amazonaws.com/xxxx/file0.mp3"
           }
       ]
    },
    {  
       "id":1,
       "name":"name1",
       "sources":[
           {
               "type":"s3",
               "url":"https://s3.amazonaws.com/xxxx/file1.mp3"
           }
       ]
    }
]

I am looking for the most effective way to store the "sources" data so that when searching for "guides" (using firebase cloud functions), the source list can be retrieved without having to make separate search queries for each element of sources.

In trying to work with Firebase Firestore, I encountered the issue where the array type does not allow a list of objects and using a "reference" returns the structure and settings of the referenced document.

function getGuides(guideId,response){
  db.collection('guides')
.where('id', '==', guideId).get()
.then(snapshot => {
    let guideDoc = snapshot.docs.map( doc => {
        return doc.data()
        })
    return guideDoc;
})

Answer №1

In your response, you mention that in Firebase Firestore, the array type does not support a list of objects.

However, this is inaccurate: it is possible to store objects in an array. Through the Firebase console, you can select the array data type and then designate each array member as a map type. Using the JavaScript SDK, you are able to save a document containing an array of objects.


Given the information above, a recommended approach for utilizing Firestore would be as follows:

  • Create a collection of guide documents
  • For every guide document within this collection:
    • Utilize the id value as the document ID;
    • Include a field called sources of array type where objects similar to those in your query are stored.

This method enables you to query your guides based on document id and retrieve the array using the code snippet provided below:

var docRef = db.collection("guides").doc(guideId);

docRef.get().then(doc => {
    if (doc.exists) {
        const sourcesArray = doc.data().sources;
        sourcesArray.forEach((element) => {
            console.log(element.type); 
            console.log(element.url); 
        });
    } else {
        // Handle scenario where document does not exist
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

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

Here is a guide on updating HTML table values in Node.js using Socket.IO

I successfully set up socket io communication between my Node.js backend and HTML frontend. After starting the Node.js server, I use the following code to emit the data 'dRealValue' to the client side: socket.emit ('last0', dRealValue) ...

Is there a way to change the label of a link in JointJS by clicking on it?

Lately, I've been facing a bit of a challenge that I can't seem to figure out. Here's the situation: What I'm aiming for is to be able to click on a link in my graph and change the label associated with it. Currently, the workaround I& ...

Striking a balance between innovation and backward compatibility in the realm of Web Design/Development

Creating websites is my passion, and I enjoy optimizing them for various platforms, devices, and browsers. However, lately, I've been feeling frustrated. I'm tired of facing limitations in implementing my creative ideas due to outdated technolog ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

How can one deactivate a <MenuItem> component in material-ui?

Currently, I am in the process of developing a personalized combo box using React and Material-UI. This unique combo box will exhibit the chosen value within the input, present a drop-down menu with various options (MenuItems), and feature a text box at th ...

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

Blending a pair of dynamic Javascript and jQuery functionalities

I have two different JavaScript/jQuery scripts that I would like to merge. One script is for a tabbed search box, which determines where the form should go when submitted. The other script is a simple JavaScript search function. My goal is to combine thes ...

Can you explain the significance of these vertices in the box geometry in THREE.js?

After creating a box geometry using the code below: const hand1geo = new THREE.BoxGeometry(2, 0.01, 0.2); const material_sidehand = new THREE.MeshBasicMaterial({ color: 0x3cc1b7 }); const sidehand = new THREE.Mesh(hand1geo, material_sidehand); ...

Converting an HTML <img> tag into a Base64 encoded image file: Step-by-step guide

Recently, I made changes to the appearance of an image by adding CSS filters using the "style" attribute of an <img> tag. <img src="myImage.png" style="filter: grayscale(100%)"> As a result, the image now has a different look and I am looking ...

Change every occurrence of multiple forward slashes to only two forward slashes

Currently, I am working with Angular 2 using TypeScript. I have an input box in HTML that allows users to enter search terms, including REST resources like employee/getDetail. I need to replace / with // to prevent my service from failing. Additionally, e ...

Scroll through the carouFredSel carousel by pressing the mouse

Looking to create a carousel that continuously scrolls when the mouse is pressed down and stops when released. Currently have a working example with hover functionality. How can I modify it to work based on mousedown instead? $("#foo2").carouFredSel({ ...

How to efficiently update a nested array within the state of a React

Although the onChange function is working as expected, I am facing issues with updating the features in the state. Despite numerous attempts, I haven't been able to find examples similar to what I'm trying to achieve, so I decided to seek help. ...

Error message encountered when submitting a form after receiving an AJAX response: VerifyCsrfToken Exception

I'm encountering an issue with my AJAX functionality that involves rendering a form with multiple input fields and a submit button. Here is the AJAX call: <script type="text/javascript"> $('#call_filter').click(function() { $.aja ...

What is the best way to sanitize or replace the $& characters (dollar sign and ampersand) within a JavaScript string that cannot be escaped?

In relation to this particular question, I find that the provided solutions do not rectify my issue. The backend (Node.js) is receiving HTML content from the frontend (React): // Here's just a demonstration const price = '<strong>US$&n ...

A guide on how to properly analyze a messy CSV file using Node.js

I am struggling to parse a CSV file due to multiple errors. I have extracted a sample for you to download here: Test CSV File The main errors causing issues are: Quotes and commas (resulting in many errors when attempting to parse the file with R) Empty ...

Improve your browsing experience by setting requirements before accessing websites

Currently on the lookout to create SCORM compliant materials for utilization in a Moodle 2.2 framework (a learning management system); sidelined by limited support for SCORM 2004 hindering page sequencing. Considering ditching SCORM for an array of standa ...

I have successfully managed to populate the Google Apps Script listbox based on the previous listbox selection for two options, but unfortunately, I am encountering issues

Struggling to set up 3 list boxes that populate based on each other? At the moment, I have one list box fetching data from a spreadsheet. Could someone assist me in configuring it so that the second list box populates based on the first, and a third list b ...

Learn the technique of looping through multiple HTML elements and wrapping them in Vue.js easily!

i need to wrap 2 HTML elements together Here is my code snippet using Vue.js <tr> <th v-for="(item9,index) in product_all" :key="item9.id"><center>Qty</center></th> <th v-for="(item99,index) in product_all" :key=" ...

Unable to expand child nodes using jstree open_node function

After loading my checkbox jstree, I want to automatically open the last accessed nodes (excluding select_node). Unfortunately, the open_node function seems to only work on the top-level parent nodes. I've attempted iterating through each node and call ...

Troubleshooting: Issues with Form Parameters in JSP

Here is the HTML form I am working with: <form action="supplierportal_home.jsp"> <select id="contract" name="contract"> <option selected="selected">Please Select</option> <option value="open" >Open</ ...