如何将阵列成功发布到Firebase数据库

问题描述

下面是我的播放器JSON的快照:

this

以下是用于选择客户端播放器的代码

$scope.history=[];
$scope.picked = [];

 $scope.buy = function(player) {
        //remove if already added locally
        var index = $scope.history.indexOf(player);
        var index2 = $scope.picked.indexOf(player.id);
        if(index>=0 || index2>=0 ){
            $scope.history.splice(index,1);
            $scope.picked.splice(index2,1);
            return;
        }
 
        //max 11 allowed
        if($scope.history.length>=10 || $scope.picked.length>=10){
            alert('max 10 players allowed');
            return;
        }
        //to make sure moeny doesn't go below $10,000,000
        if($scope.total<0){
            alert('Oops! You have run out of cash');
            return;
        }
 
        var selected = $scope.history.reduce(function(a,b){
            a[b.position] = (a[b.position] || 0) + 1;
            return a;
        },{}) || {};
 
        if(!selected[player.position] || selected[player.position]<4 && 
            $scope.total>0){
            $scope.history.push(player);
            $scope.picked.push(player.id);
               
        }else{
            alert('You can add only four players per position');
             
        }
      };

代码产生以下选定的播放器(例如):

[
0: {Team: "AC Izzue",assists: 0,cost: "5m",goals: 0,id: 1,…}
1: {Team: "AC Izzue",id: 2,…}
2: {Team: "AC Izzue",id: 3,…}
3: {Team: "AC Izzue",id: 4,…}
4: {Team: "AC Izzue",id: 5,…}
5: {Team: "AC Izzue",id: 6,…}
6: {Team: "AC Izzue",id: 7,…}
7: {Team: "After Hours FC",id: 16,…}
8: {Team: "Alaye FC",id: 27,…}
9: {Team: "Alaye FC",id 26}
]

每次我尝试pushset这个选定的玩家数组进入我的firebase数据库时,都会出现以下错误

错误:Reference.push失败:第一个参数在属性'users.UhIBZDBaLcTcesdRiJ9u7xYv9bd2.picked.0'中包含无效的键($ id)。键必须是非空字符串,并且不能包含“。”,“#”,“ $”,“ /”,“ [”或“]”

是否可以将阵列成功发布到Firebase上的用户身上,或者必须更改阵列?

解决方法

要理解您的问题的代码并不容易,因为它取决于其他几个变量和值。

如果要在Firebase Realtime数据库中获取问题所附屏幕快照中显示的内容,则需要将对象数组传递给set()方法,如下所示:

  firebase
    .database()
    .ref('players')
    .set([
      { Team: 'AC Izzue',assists: 0,cost: '5m',goals: 0,id: 1 },{ Team: 'AC Izzue',id: 2 },]);

如果您使用push()方法(似乎是由于收到的错误而引起的),则将使用自动生成的密钥创建一个新的子位置,并以类似以下内容的结尾:

   "players" : {
    "-MESdJeoccFv8mc5Qhhd" : [ {  // <=== auto-generated key
      "Team" : "AC Izzue","assists" : 0,"cost" : "5m","goals" : 0,"id" : 1
    },{
      "Team" : "AC Izzue","id" : 2
    } ]
  }