What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure:

var newItem = {
            'address': "Кабанбай батыр, 53",
            'cityId': 1,
            'courierName': "Максат",
            'dispatcherId': "somedispatcherId",
            'info': "привезти к 2ому подъезу в 11 ч вечера", 
            'isCompleted': 0,
            'isProceeded': 0, 
            'name': "Адиль Жалелов" ,
            'paymentMethod': "наличка" ,
            'phone': "87775634456" ,
            'price': 5000,
            'products': []
        }

The issue I am facing is that I cannot push an array of objects ($scope.orders) to the newItem.

I have attempted to push this $scope.orders:

   $scope.addOrder = function(){
        var orderRef = 
        firebase.database().ref().child('Orders').child('Astana');
        var newOrderKey = orderRef.push().key;
        var newJson = {
            'address': "Кабанбай батыр, 53",
            'cityId': 1,
            'courierName': "Максат",
            'dispatcherId': "somedispatcherId",
            'info': "привезти к 2ому подъезу в 11 ч вечера", 
            'isCompleted': 0,
            'isProceeded': 0, 
            'name': "Адиль Жалелов" ,
            'paymentMethod': "наличка" ,
            'phone': "87775634456" ,
            'price': 5000,
            'products': []
        };
         newJson['products'].push( $scope.orders);
        /*for (var i =0; i < $scope.orders.length ; i++){
            newJson['products'].push( $scope.orders[0]);
        } */

        console.log($scope.orders,newJson)
        orderRef.child(newOrderKey).set(newJson); 
    } 

Unfortunately, I encountered an error: Reference.set failed: First argument contains an invalid key ($$hashKey) in property....

When I log $scope.orders, I get:

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

If anyone has any insights or can offer assistance, it would be greatly appreciated!

Thank you in advance!

Answer №1

When using Firebase, the Push method can be used to create a new child location with a unique key and obtain its Reference. This means you will already have both the child and its reference without needing to manually add the child to your orderRef as attempted previously.

To achieve this, simply use the following code:

var newOrderKey = orderRef.push();  // Returns the reference of the future child
newOrderKey.set(newJson); 

There is also a known issue related to objects from Angular which involves the '$' character in '$$hashKey'. This problem arises because Angular automatically creates the $$hashKey properties.

The solution to this issue is as follows:

newJson['products'].push(angular.fromJson(angular.toJson($scope.orders))); 

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

The unpredictability and variability of AngularJS templateURL values

I'm currently working on a "name" directive that can accommodate both first and last names. Here is the code I have so far: index.html <div data-dm-name label="First Name:" info="first_name"></div> <div data-dm-name label="Last Name: ...

Styling in CSS is being applied to a button element within a React component,

Having trouble with a button styled with the className 'actions' The button displays the CSS styling from '.actions', but not '.actions button'. Both should be applied. This code snippet works for all elements ...

Aggregate the values in each position across various arrays and merge them into distinct arrays

I'm facing an issue that I can't seem to solve on my own. Imagine we have several arrays: [1,2,3] [1,2,3] [11,12,13] How do I go about extracting all the values at each index from these multiple arrays and combining them into separate arrays? T ...

Updating Time by Adding Minutes using ngFor Loop in Angular 4

I'm currently developing a scheduler that requires user input for start time and the time between two games. I am looking to display the time in a loop using ngFor, incrementing by minutes each time. How can I accomplish this within an Angular 4 HTML ...

Exploring ways to personalize the parsing of url query parameters in express.js

When using req.query, the hash of query parameters is returned. Additionally, if a parameter consists of a JSON object, it is automatically parsed into JSON format, which is quite impressive. However, I am curious about customizing this parsing process. I ...

Verify Radio Buttons in AngularJS

I thought validating a selection from a radio group would be simple, but I'm struggling to find the right solution. In my form, I need to ensure that at least one option is selected from the radio buttons. Using the 'required' attribute on e ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Retrieve the HTML representation of a progress bar in Ext JS 3.4 prior to its rendering

Is it possible to obtain the HTML representation of a progress bar before it is rendered anywhere? I am currently using a custom renderer for rendering a progress column in a grid: renderer: function( value, metaData, record, rowIndex, colIndex, store ) ...

Combining meshes results in a lower frame rate

I have combined approximately 2500 meshes, each with its own color set, but my FPS is lower than if I had not merged them. Based on THIS article, merging is recommended to improve FPS performance. Is there something I am overlooking? var materials = new ...

Creating a customized plugin in JavaScript that utilizes a local JSON/GeoJSON file

I am relatively new to Drupal and currently working on developing a custom map module. While my module functions correctly and displays the map along with relevant information, I encountered a challenge regarding calling my geojson file using a hard-coded ...

Issue: Inability to scroll on div overflow section

My website consists of one static page with an HTML and CSS file. Oddly enough, when testing the page and inputting content into a multiline textarea until it overflows, the browser fails to display a scrollbar. Despite inspecting the div with the id &apos ...

Issue with disabling checkboxes in jsTree

Currently utilizing the latest version of jsTree in one of my applications. I would like to have specific checkboxes disabled by default. To achieve this, I am referencing this resource. The jstree code I am using is as follows: $("#"+"div_"+aspectid).js ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

What is the reason behind only the initial option showing up in the selection when utilizing ng-options?

When using ng-repeat to populate a select element and adding two options below it, only the first option appears. What could be causing this issue? For example: <select id="dropDownSelect", ng-model="chosenDash.id", ng-options="dashboard._id as ...

Tips for showcasing my database in real-time using Php, JavaScript, jQuery and AJAX

Is there a way to display my MySQL database in real-time through AJAX without overloading it with excessive queries? I am currently utilizing jQuery's load function, but I suspect there may be a more efficient method. Can you offer any advice or alter ...

Receiving the error message "SyntaxError: Unexpected token {" while attempting to send JSON with an AngularJS HTTP POST request

RESOLVED: After troubleshooting, I discovered that the issue was caused by the second echo statement in my PHP script. Once I removed it and only kept the first one, everything worked smoothly. I'm facing a problem while trying to make a simple post ...

Can a placeholder dropzone be created at the bottom of Vue Draggable lists?

Currently, I am utilizing Vue.Draggable (accessible at https://github.com/SortableJS/Vue.Draggable) to develop a kanban board that enables me to drag items from one list to another. A challenge I face is that when dragging a list item to the bottom of anot ...

Maintaining the position of the input cursor when using the arrow up and down keys in AngularJS directive

I am currently developing a custom "typeahead/autocomplete" directive. element.bind("keydown keypress", function (event) { if(event.which === 38 || event.which === 40) { var increment = event.which === 38 ? 1: -1; ... .. ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...