Aralbay Issatayev Aralbay Issatayev - 2 months ago 20
AngularJS Question

How to push array into json object in Firebase set() function?

I want to push new item to my firebase database.

Json object should look like this:

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


And the problem is that i cant push array of objects($scope.orders) to newItem

i tried 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);
}


But i got error : Reference.set failed: First argument contains an invalid key ($$hashKey) in property....

if console.log($scope.orders) then get

xcxx

Anyone who can help?

thanks in advance!

Answer Source

In Firebase, Push method generates a new child location using a unique key and returns its Reference. So you already have the child and the reference of your child. You don't need to add a child to your orderRef like you tried.

You can simply do that

var newOrderKey = orderRef.push();  // Return the ref of the futur child
newOrderKey.set(newJson); 

Also there is an issue with object from angular, the '$' in '$$hashKey' is the issue. Angular creates the $$hashKey properties.

This should fix the issue

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