What is the best way to iterate through an array of data fetched from a Firebase database using a forEach loop in JavaScript?

Here is the layout of my database:

https://i.sstatic.net/yWyUJ.png

I am currently working on a firebase function that iterates through each barbershop and retrieves all their respective Barbers.

In the code snippet below, I have successfully fetched all the barbershop names and stored them in an array, which is then displayed in the console like this:

https://i.sstatic.net/luMVl.png

However, when trying to progress to the next stage of my function, none of the code within "barberShopArray.forEach((key)" seems to be executing, and even "console.log(key)" does not work.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

var database = admin.database();

exports.addTimeNod2 = functions.pubsub.schedule('every 24 hours').onRun((context) =>
    {

        var num = 1;
        let barberShopArray = [];
return database.ref('/BarberShops/').once("value").then((snapshot) =>
            {
                snapshot.forEach((childSnapshot) =>
                    {
                        barberShopArray.push(childSnapshot.key);
                    });
                console.log(barberShopArray);
                return barberShopArray;
            }).then(barberShopArray.forEach((key) =>
                {
                    console.log(key);
                    database.ref('/BarberShops/' + key + '/Barbers/Barber1/').once("value").then((snapshot)=>
                        {
                            if(snapshot.exists())
                            {
                                database.ref('metadata/shop' + num +'/').set(key);
                                num++;
                            }
                            return null;
                        }).catch((error)=>
                            {
                                console.log(error);
                                return error;
                            });
                    return null;
                }));
    });

Answer №1

In my scenario, I implemented the following code snippet:

const database = firebase.database().ref();

    database.child("orders")
        .get()
        .then((snapshot) => {
            if (snapshot.exists()) {
                const orders = [];

                for (let key in snapshot.val()) {
                    orders.push({ ...snapshot.val()[key], id: key });
                }
          })

To see more examples, feel free to visit this link within my repository.

Answer №2

It seems like the issue you are facing is due to a redundant return statement in your code. The line console.log(barberShopArray) is functioning as expected, but the subsequent use of return barberShopArray before barberShopArray.forEach((key) is causing the following function logic to never execute. To resolve this problem, simply remove the unnecessary return statement and also eliminate the need for the then() method after it. Making these changes will ensure that your code runs smoothly and updates the metadata successfully.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
exports.addTimeNod2 = functions.pubsub.schedule('every 24 hours').onRun((context) => {
   var num = 1;
   let barberShopArray = [];
   return database.ref('/BarberShops/').once("value").then((snapshot) => {
       snapshot.forEach((childSnapshot) => {
           barberShopArray.push(childSnapshot.key);
       });
       console.log(barberShopArray);
       barberShopArray.forEach((key) => {
           console.log(key);
           database.ref('/BarberShops/' + key + '/Barbers/Barber1/').once("value").then((snapshot) => {
               if (snapshot.exists()) {
                   database.ref('metadata/shop' + num + '/').set(key);
                   num++;
               }
           }).catch((error) => {
               console.log(error);
               return error;
           });
       });
       return null;
   });
});

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

Passing slots to child components within a VueJS application - A helpful guide

Within my application, I frequently utilize a list and list_item component. To provide a general idea: contact_list.vue <template lang="pug"> .table .table-header.table-row .table-col Contact .table-col Info .tabl ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

JavaScript: How can I remove it when I click anywhere on the webpage with onClick?

A challenge I'm facing involves creating a form with an input field that changes its border color when clicked. My goal is for the border to return to its original color when clicking anywhere else on the page. -HTML <form action=""> ...

When the condition within the click function is met, concatenate the variable

I'm currently working on a function that involves adding "http://" to the variable 'bar' if it's not already included. This modified 'bar' value will then be sent via ajax to be inserted into the database and also displayed ba ...

The custom pagination feature in MUI DataGridPro does not display the rowsPerPageOptions dropdown as expected

I am currently utilizing React in my project. "react": "^18.2.0", "@mui/material": "^5.10.7", "@mui/x-data-grid-pro": "^5.16.0" An issue arises with the visibility of the rowsPerPageOptions dr ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

Trouble with console.log and document.addEventListener, they just won't cooperate

I'm currently working on a phonegap application for IOS. I was able to successfully create the project and when running the initial application, everything worked perfectly. However, when I tried to add my own code, it seems that none of the javascrip ...

Choosing the type attribute of an input tag by using a javascript variable as a condition: What's the best approach?

I am currently utilizing an input tag on the client side to receive text input. <input type="text" class="form-control" placeholder="Enter Message" id="messageText" autofocus/> My goal now is to dynamically set the type attribute based on a Javasc ...

Create a PDF and excel sheet, with the excel sheet having neither the ability to open nor the option to save similar to how it is done in Laravel

Is there a way to create an Excel sheet in Node.js that can be opened directly or saved to the system, without saving it in the project directory? Generating Excel Sheet exports.excel = function (req, res) { var fs = require('fs'); var e ...

What causes the statement to be executed before the database transaction?

How can I ensure that the state domains are set only after all DB transactions are completed in my code? Please provide guidance on how to perform this operation correctly. I am using the following method to update the new domains array: setFavorites() { ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

Allow users to copy and paste on a website where this function is typically restricted

Just wanted to mention that I have very little coding knowledge, so I appreciate your patience. I'm attempting to paste something onto a site that doesn't allow it. Here is the link to the javascript they used to block it: A friend of mine recom ...

What is the best way to navigate through individual child elements within a parent container that is scrollable?

I'm currently working on a unique user interface that features a scrolling list of options. The goal is for users to easily find and select the option they are looking for by simply scrolling or swiping. However, I've encountered an issue where ...

Tips for passing parameters to an ajax request in Django URL?

In my current setup, I'm passing a URL to the ajax like this: $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://loc ...

Choose Select2 to remove all selected options

I'm looking for a way to remove all selected values in one click without having to specify each individual 'id' separately. I've tried experimenting with different approaches, but so far, I've only been able to deselect the first ...

Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect. Below is the HTML search ...

Simple JavaScript File Loading without Rendering or Running Laravel 8 Bootstrap 5

Hey there, I just set up a fresh laravel and bootstrap project. All I've done so far is create a navigation bar. However, when I load the page, I noticed that the app.js file is loading but the CSS is not rendering properly because the app.css stylesh ...

Troubleshooting UV Mapping Problem in THREEJS JSON Model

After reviewing the json file for a 3D model, I came across the following line: "uvs": [[-3.21834,-1.65399,-3.21834,-2.57657,4.21834,-2.57657,4.21834,-1.65399,4.21834,-1.85233,4.21834,-2.7749,-3.21834,-2.7749,-3.21834,-1.85233,4.21834,0.961286,-3.21834,0 ...