Using a function to send multiple child data in Firebase

I am trying to figure out how to save data to a Firebase multi-child node structure:

--Events
----Races
-------Participants

Below is some dummy data example that represents the type of data I need to store in Firebase:

  var dummyData = [
            {
                event_id: 1,
                event_venue: "Churchill Ground Venue",
                event_name: "Victoria Cup",
                event_type: "Holiday Special",
                event_datetime: now,
                event_url: 'www',
                races: {
                    1: {
                        race_id: 1,
                        race_type: "Horse Race",
                        race_url: "www",
                        race_name: "Super Hourse 8",
                        race_venue: "Ground No 7",
                        race_datetime: now,
                        races_participants: {
                            1: {
                                participants_id: 1211,
                                participants_name: "Doll Fire",
                                participants_place_odds: 10,
                                participants_win_odds: 5,
                                participants_result: 0,
                            }
                        }
                    },
                    2: {
                        race_id: 2,
                        race_type: "Horse Race 2",
                        race_url: "www",
                        race_name: "Super Hourse 9",
                        race_venue: "Ground No 7",
                        race_datetime: now,
                        races_participants: {
                            participants_id: {
                                participants_id: 222,
                                participants_name: "Doll Fire 2",
                                participants_place_odds: 130,
                                participants_win_odds: 54,
                                participants_result: 03,
                            }
                        }
                    }
                },
            },
        ];

 //calling Services to post data
  EventsFactory.postEvents(dummyData[0]);

  myApp.factory('EventsFactory', function(){
    var factiry = {};
     //post data to fb server
    factory.postEvents = function (data) {
        //passed data must be object
        var firebaseRef = new Firebase("https://api.firebaseio.com/");

        firebaseRef.child("events").push({
            event_id: data.event_id,
            event_venue: data.event_venue,
            event_name: data.event_name,
            event_type: data.event_type,
            event_url: data.event_url,
            event_datetime: data.event_datetime,
            races: {
              //not sure how to store multiple child, Cant call for each to loop 
              //each paased object from data var
                race_id: {
                    race_id: data.races.race_id,
                    race_type: data.races.race_type,
                    race_url: data.races.race_url,
                    race_name: data.races.race_name,
                    race_venue: data.races.race_venue,
                    race_datetime: data.races.race_datetime,
                    races_participants: {
                        participants_id: {
                            participants_id: data.races.races_participants.participants_id,
                            participants_name: data.races.races_participants.participants_name,
                            participants_place_odds: data.races.races_participants.participants_place_odds,
                            participants_win_odds: data.races.races_participants.participants_win_odds,
                            participants_result: data.races.races_participants.participants_result
                        }
                    }
                }
            },
        });
    }
    return factory;
  });

I'm struggling with why the push method isn't saving the entire array of data and pushing it to Firebase, along with all its child elements.

Currently, I am encountering the error message: Cannot read property 'participants_id' of undefined at Object.factory.postEvents However, all values are present in the data array.

Answer №1

If you want to efficiently store data in Firebase, avoid pushing the entire event at once. Instead of using array indices for child nodes on the server, it is recommended to push each item individually into Firebase and let the platform generate unique IDs for you.

In order to properly structure your data, you will need to loop through and push each event, race, and participant separately. Below is a code sample demonstrating this:

    // Add the event
    var event = firebaseRef.child("events").push({
        event_id: data.event_id,
        event_venue: data.event_venue,
        event_name: data.event_name,
        event_type: data.event_type,
        event_url: data.event_url,
        event_datetime: data.event_datetime
    });

    // Add races to the event
    data.races.forEach(function(race) {
        var newRace = event.child("races").push({
            race_id: race.race_id,
            race_type: race.race_type,
            race_url: race.race_url,
            race_name: race.race_name,
            race_venue: race.race_venue,
            race_datetime: race.race_datetime,
        });

        // Add participants to the race
        race.race_participants.forEach(function(participant) {
            newRace.child("participants").push({
                participants_id: participant.participants_id,
                participants_name: participant.participants_name,
                participants_place_odds: participant.participants_place_odds,
                participants_win_odds: participant.participants_win_odds,
                participants_result: participant.participants_result

            });
        });
    });

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

Tips for setting up listeners across multiple modules using socket.io

Last year, I created a multiplayer game using node.js and socket.io. Now, as part of my efforts to enhance the game, I am working on breaking down the code into modules. Currently, I am utilizing expressjs 4.4 along with socket.io 1.0. One challenge I enco ...

What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page Within my code, there is a div called #myDiv that defaults to an opacity of 0. Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below: #myDiv { opacity: 0; } #myDiv:hover { opacity: 1 ...

Discovering the correct location within a complex JSON or array to perform updates using JavaScript (either AngularJS or vanilla JavaScript

I am currently facing a challenge where I need to search for a specific value within my complex JSON array and then update the corresponding object. Here is a snippet of my JSON array: var myArray = [{ "id": 5424, "description": "x ...

Angular JS Array with N-level hierarchy

I am developing an application for questionnaires, where questions have responses that can lead to child questions with even more responses. This creates a hierarchical structure of multiple levels. I am looking for the best strategy to display this data i ...

Facing a problem with the carousel in Angular 6

I am currently working with Angular 6 and I have a topAdvertisementList[] that is supposed to return 2 records to be displayed in my carousel with a fixed image, but for some reason, only one record is showing up in the carousel! I suspect there might be a ...

What is the process for saving an HTML document with SaveFile.js?

I'm currently implementing a save feature for my website. Utilizing the 'SaveFile.js' module from this link: 'https://github.com/eligrey/FileSaver.js/' Once the user clicks on the save button, the goal is to have the entire documen ...

Is it possible to verify if each input is unique using the parsley validator?

As a novice, I am struggling with a task where I have 6 School Children IDs. The teacher needs to input these IDs, and while it's not vital for him to enter all of them, he must input at least one. Furthermore, if he decides to input more than one ID, ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...

Challenges Encountered When Working with React.useState()

I am facing an issue where a new row is not appearing after clicking the button. Although the console.log output indicates that the row was added correctly to the tables variable. Another concern I have is why I can see the new row added to the table even ...

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

Enhancing bar chart presentation with text in d3

Looking to enhance my bar chart by adding text tooltips that appear when hovering over each bar. While I am a beginner with d3, I've been struggling to implement this feature effectively. Despite trying various methods gleaned from online resources, t ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

What is the process for submitting data using AJAX in Django?

I am facing an issue with my dynamically updating form. When I submit the form, I want to post the data to a views function and receive a response. Below is the code from my template file: $("#myForm").submit(function(){ event.preventDefault(); va ...

Angular NVd3 barChart with multiple bars

I am trying to implement the nvd3 angular multiBarChart, but I am struggling with the lack of documentation. Despite searching on Google and Stack Overflow, I haven't found a solution that fits my specific scenario. My question pertains to how to stru ...

Watching for changes in AngularJS is causing errors on my page

Just starting out with Angular and trying to run examples from a book. I've been working on an example involving the $watch method, and everything was running smoothly with the initial code: <html ng-app> <head> <title>StartUp C ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Switching from the global import module pattern to ES6 modules

In recent years, my approach to JavaScript development has involved using the global import method. Typically, I work with a set of utility functions packaged and passed to a separate site module containing individual functions for each web functionality: ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

What is the best way to handle processing large amounts of data stored in a file using JavaScript within the

Suppose my file contains the following data and is located at /home/usr1/Documents/companyNames.txt Name1 Name 2 Name 3 Countless names... I attempted to use this code: $> var string = cat('home/usr1/Documents/companyNames.txt'); $> s ...