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

JavaScript encounters an error when trying to create a MarkLogic instance with an array

[javascript] XDMP-CAST: (err:FORG0001) xs:string#1(.) -- Invalid cast: `json:object(<json:object xmlns:xs="http://www.w3.org/2001/XMLSchema" ` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>) cast as xs:string Stack Tr ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

What is the best way to display the nested information from products.productId?

How do I display the title and img of each product under the product.productId and show it in a table? I attempted to store the recent transaction in another state and map it, but it only displayed the most recent one. How can I save the projected informa ...

Changing or toggling the visibility of links once the week is finished

I have a total of 4 links available, but I want to display only one link at a time, highlighting a different lunch option every week. Once all 4 weeks have passed, the first lunch menu will be shown again, starting from Monday. <div class="wrapper& ...

What causes an undefined outcome when a promise is fulfilled?

Could you help me understand something? const promise1 = new Promise((resolve, reject) => { setTimeout(() => { if(true) { resolve('success') } else { reject('failure') } }, 4000) }) promise1.then(resul ...

Tips for utilizing date objects instead of date 'strings' while still obtaining the desired outcome

Below is a schema that I am working with: var MySchema = new Schema ({ event: { full: String, date: String, name: String, } }); To illustrate, here are some examples of the values: event.date = '16/02/20 ...

Leveraging oEmbed - JSON data (within client-side JavaScript)

Is it feasible to utilize an oembed provider that solely produces json and xml outputs on the client side using javascript (through a $.ajax request to the provider)? Do we need to rely on oembed providers that enable a jsonp callback in javascript for th ...

The axios GET request failed to return a defined value

My current issue involves making a get request using the following code snippet: router.get('/marketUpdates',((request, response) => { console.log("market updates"); var data: Order[] axios.get('http://localhost:8082/marketUpdates& ...

Understanding how to set the Content-Type in a Post request using Ajax with Node.js

Attempting to send an ajax request without a header in Node.js triggers an error: { [Error: unsupported content-type] status: 415, statusCode: 415 } However, when sending a request with a header, Node.js does not seem to respond. Here is my ajax funct ...

Submission of the form was cancelled, causing a loop to occur

I'm encountering an issue with submitting a file through a standard HTML form. After uploading the file, the process seems to get trapped in a continuous loop where the file keeps uploading repeatedly. The submission of the form is done using jQuery, ...

The Discord.js error message popped up, stating that it was unable to access the property 'then' since it was undefined

I'm currently working on implementing a mute command for my discord bot, but I'm encountering an error that says; TypeError: Cannot read property 'then' of undefined I am unsure of what is causing this issue and would greatly apprecia ...

What is the standard root directory in the "require" function's context?

After spending hours struggling to set up a simple "require" command, I've come to the conclusion that var example = require("example") only works if there's an example.js file in the node_modules directory of the project. I'm encountering ...

How React Utilizes Json Arrays to Add Data to a File Tree Multiple Times

For some reason, when attempting to add data to a file tree, it seems to duplicate the data sets. I'm not entirely sure why this is happening. Here's an example of the simple json array I am working with: export const treeDataFile = [{ type: & ...

Is there a way to incorporate arguments into my discord.js commands?

Hey there! I'm looking to enhance my Discord commands by adding arguments, such as !ban {username}. Any tips or guidance on the best approach for this would be amazing! const Bot = new Discord.Bot({ intents: ["GUILD_MESSAGES", "GUIL ...

How can I update the title of the NavigationBarRouteMapper without altering the current route in React Native?

Here is a snippet of code that outlines the NavigationBarRouteMapper: var NavigationBarRouteMapper = { ... , RightButton(route, navigator, index, navState){ return( <TouchableHighlight onPress={()=>{ //When this ...

Is there a way to format wrapped lines with indentation in an unordered list?

Is there a way to indent the wrapped lines of text in an unordered list? The current layout is not quite what I want, as shown in the first image below. Ideally, I would like it to look more like the second image. I attempted to use margin-left: 56px; and ...

It seems like there may be an issue with the React Table Pagination in reactjs

As a newcomer to React JS, I have been utilizing react-table to create a component that can filter, sort, and paginate sample data from a JSON file. If you are interested in the tutorial I am following, you can find it here: Currently, I am encountering ...

When viewing my project on GitHub pages, the images within the card are not appearing

After running my project page link at https://nayaksofia.github.io/RestaurantReviewTest1/, I've noticed that the images inside the card are not displaying. However, when I run the same project on my local server localhost:8000, the images appear just ...

What is the best way to incorporate products as components into the cart component?

ProductCard import React from 'react'; import { Card, Container, Row, Col, Button} from 'react-bootstrap'; import Cart from './Cart'; import './ItemCard.css'; function ProductCard(props){ return( <Car ...

What is the process behind managing today's Google image of the day?

After coming across the javascript picture control on the Google search page, I became interested in replicating it myself. The feature zooms in on a picture when hovering over it, but I couldn't locate the HTML code they were using for it. Is there ...