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:

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

Integrate jQuery-ui into your Angular 5 application

Having some trouble integrating jquery-ui into my Angular 5 project. I need to use a feature that requires jquery-ui, but I keep encountering this error: TypeError: WEBPACK_MODULE_10_jquery(...).droppable is not a function I initially attempted to plac ...

"Discrepancy found in results between Node-Fetch POST and Firefox POST requests

I have encountered a challenge while trying to replicate a successful log-in process on a website using node-fetch after being able to do so with Firefox. The login process consists of three stages: Visiting /login which returns a sessionToken from the we ...

Utilizing Ajax to update the login form without reloading the page and displaying any errors

I have created a login form that utilizes ajax to handle login errors such as "incorrect password" from my login.php file. Instead of reloading a new page with the error message, it now displays the errors on the same login form, which is working perfectly ...

What is the best way to create a reactive prop within this Vue 3 application?

I've been developing a news application using Vue 3 along with the News API. My current focus is on implementing a search feature. Within my App.vue file, I have: <template> <TopBar @search="doSearch" /> <div class=" ...

Issue with font selection in Fabric.js

I am currently working with fabric js version 1.7.22 alongside angular 7 to create a text editor. I have encountered an issue when trying to add text to the canvas using a custom font as shown in the code snippet below. var canvas= new fabric.Canvas(&apos ...

Retrieving a attribute from an element on a separate webpage

On my website, I have a list of links that use ajax to load new pages. Each of these new pages features a gallery of images with a main image. I am trying to figure out how to extract the source URL from the main image in order to display it as a thumbn ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...

When requesting a Node.js API from Javascript fetch, the session custom property is throwing an undefined error

I am currently working on a User Login Project, where the APIs are built using Node.js and Express. The UI part is developed using HTML and JavaScript, with these components existing as separate projects. Upon user login, a fetch call is made in JavaScrip ...

Tips for refreshing a DOM element after inserting with jQuery

I'm trying to update the LI element after using the insertBefore function in jQuery. The issue arises after adding new elements to UL where I encounter difficulty deleting the same element (using emailTagRemove). Check out the demo to see the proble ...

Troubleshooting Error 405 in AJAX, Javascript, Node.js (including Body-Parser and CORS), and XMLHttpRequest

I have been working on creating a JSON file from buttons. While I am able to retrieve data from the JSON files that I created, I am facing issues with posting to them using XMLHttpRequest and Ajax. Interestingly, I can add to a JSON file using routes just ...

Extracting the console.log method from the console

Given that the console object has not been overridden and refers to a native object, the console.log method (and possibly others) is obtained from the console object with the following code: var log = obj.log = console.log; // instead of console.log.bind( ...

Filtering a list with Vue.js using an array of checkboxes

Currently, I am exploring ways to filter a v-for list using a checkbox model array with multiple checkboxes selected. Most examples I have come across only demonstrate filtering one checkbox at a time. In the demo here, you can see checkboxes 1-3 and a lis ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

Having issues with displaying options in Select2 within a Vue Component?

I have successfully created a Vue component that generates options for a select dropdown as shown below: <select ref="subdomain_id" name="subdomain_id" id="newEvidenceSubdomain" class="form-control" :class=&qu ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

Integrate JavaScript date into the gulp-rev workflow

I have been encountering an issue while using the gulp-rev plugin to add a revision of my app/html page generated by the Yeomann webapp generator. My workflow involves zipping the app and then adding a revision, but I am having trouble replacing the hash t ...

JavaScript form submission failing to transmit updated data

I have been working on a JavaScript function that changes the hidden value of a form based on which button is clicked, and then sends it via post to a processing page. Even though I have confirmed that the value is being changed correctly, when the post i ...