如何在Firebase中推送多个项目?

时间:2019-01-07 14:30:20

标签: javascript firebase firebase-realtime-database

我有一个对象数组。我想做的就是将所有项目推送到数据库中的特定位置,因为通过push调用,每个项目都将被分配一个唯一的ID。

我尝试将Firebase推入循环内,但我认为这样做不正确。 (此处为网络应用)

const array = [{title: 'one'},{title:'two'}, {title: 'three'}]

array.map(item => {
          FirebaseRef.child(`boards/${boardId}/containers`).push(item)
})

1 个答案:

答案 0 :(得分:2)

以下使用update()方法将起作用:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>MAPS 1 MENU</title>
    <link rel="stylesheet" href="styles.css">
  </head>

  <body style="width:850px">
    <script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      google.charts.load('current', {
        packages: ["geochart"],
        mapsApiKey: 'AIzaSyB5KSY9RtRmKv3Kzf1hsdzzRGZktpsUqEQ'
      });

      google.charts.setOnLoadCallback(drawRegionsMap);

      var data1;
      var data2;
      var data3;

      $(function() {
        $(".preload").fadeOut(4500, function() {
          $(".content").fadeIn(1000);
        });
      });




      function handleQueryResponseTR(response1, divId) {
        if (response1.isError()) {
          alert('Error in query: ' + response1.getMessage() + ' ' + response1.getDetailedMessage());
          return;
        }
        data1 = response1.getDataTable();
        var colorValues = [];
        var numRows = data1.getNumberOfRows();
        for (var i = 0; i < numRows; i++) {
          colorValues.push(parseInt(data1.getValue(i, 15)));
        }
        //assign color to colorValues
        var colorNames = [];
        colorValues.forEach(function(value) {

          if (value <= 1) {
            //1(E)PR framework legislation in place//
            colorNames.push('#ffff57');

          } else if ((value > 1) && (value <= 2)) {
            //2(E)PR legislation in planning//
            colorNames.push('#ffff9b');

          } else if ((value > 2) && (value <= 3)) {
            //3//Alternative model with producer funding
            colorNames.push('#3FE5C9');

          } else if ((value > 3) && (value <= 4)) {
            //4// Alternative model – not producer funded
            colorNames.push('#B97A57');

          } else if ((value > 4) && (value <= 5)) {
            //5// Competing organisation model
            colorNames.push('#85C9F3');

          } else if ((value > 5) && (value <= 6)) {
            //6//Competing organisation model with coordination centre
            colorNames.push('#3DA9EC');

          } else if ((value > 6) && (value <= 7)) {
            //7/ Competing organisation model with eco-tax back-up
            colorNames.push('#DFA6FF');

          } else if ((value > 7) && (value <= 8)) {
            //8 Different EPR models by product category or other criteria
            colorNames.push('#99F1E2');

          } else if ((value > 8) && (value <= 9)) {
            //9 None - but municipalities responsible for sep. collection
            colorNames.push('#9edae5');

          } else if ((value > 9) && (value <= 10)) {
            //10 None - but other obligations for producers
            colorNames.push('#d1d19d');

          } else if ((value > 10) && (value <= 11)) {
            //11 Other model
            colorNames.push('#9edae5');

          } else if ((value > 11) && (value <= 12)) {
            //12 Recycler centric model
            colorNames.push('#9edae5');

          } else if ((value > 12) && (value <= 13)) {
            //13 Single organisation model
            colorNames.push('#98df8a');

          } else if ((value > 15) && (value <= 16)) {
            //16 under other jurisdiction
            colorNames.push('#e2dace');

          } else {
            colorNames.push('#ffaf87');

          }
        });
        var view1 = new google.visualization.DataView(data1);
        view1.setColumns([16, 15,
          {
            type: 'string',
            role: 'tooltip',
            properties: {
              html: true
            },
            calc: function(dt, row) {
              var country = dt.getFormattedValue(row, 5)
              var policy = dt.getFormattedValue(row, 6)
              var dataname = dt.getFormattedValue(row, 8)
              var dropname = dt.getFormattedValue(row, 9)
              var formatter = new google.visualization.DateFormat({
                pattern: "MMMM yyyy"
              });
              var startdate = formatter.formatValue(dt.getValue(row, 10));
              //var startdate = dt.getFormattedValue(row, 10)
              var comment = dt.getFormattedValue(row, 12)
              //colorValues.push(dt.getFormattedValue(row, 6))
              if (dropname != 'EPR policy not in place') {
                return '<br><div id="country">' + country + " - " + policy + '<br><br></div> ' +
                  '<div id="header1">Dominant (E)PR policy model:<br></div>' +
                  '<div id="dropname">' + dropname + '<br><br></div>' +
                  '<div id ="header2">Since :&nbsp;</div><div id="date">' + startdate + '</div><br><br><br>' +
                  '<div id ="comment">' + comment + '<\/div>'
              } else {
                return '<br><div id="country">' + country + " - " + policy + '<br><br></div> ' +
                  '<div id="header1">Dominant (E)PR policy model:<br></div>' +
                  '<div id="dropname">' + dropname + '<br><br></div>'
              }
            },

          }
        ]);
        var chart1 = new google.visualization.GeoChart(document.getElementById(divId));

        google.visualization.events.addListener(chart1, 'select', function() {

          var selection = chart1.getSelection();


          var dropname = data1.getValue(selection[0].row, 9);
          //alert(dropname);
          if (dropname != 'EPR policy not in place') {


            var cnid = data1.getValue(selection[0].row, 0);
            var polid = data1.getValue(selection[0].row, 1);
            var strid = data1.getValue(selection[0].row, 2);
            var sid = (strid) - 1;

            var statecode = data1.getValue(selection[0].row, 4);
            //if (selection.length > 0 && dropname != '(E)PR policy in planning' ) {
            //http://www.sagisepr.com/country.php?country=21&polsel=1&sid=17&statecode=AR
            //http://www.sagisepr.com/v3/country.php?country=38&statecode=US-ME&t=2&polsel=1&sid=1
            window.open("http://www.sagisepr.com/v3/country.php?country=" + cnid + "&statecode=" + statecode + "&t=2" + "&polsel=" + polid + "&sid=" + sid);
          }
        });

        var options1 = {


          colorAxis: {
            colors: colorNames,
            values: colorValues
          },


          backgroundColor: {
            fill: '#FFF'
          },
          datalessRegionColor: '#F5F0E7',
          displayMode: 'regions',
          legend: 'none',
          enableRegionInteractivity: 'true',
          resolution: 'countries',
          //sizeAxis: {minValue: 1, maxValue:1,minSize:10,  maxSize: 10},
          region: 'null',
          keepAspectRatio: false,
          width: 800,
          height: 480,
          tooltip: {
            isHtml: 'true',
            textStyle: {
              color: '#444444'
            },
            showTitle: false
          }
        };
        //radio button

        // init regions
        var regions = document.getElementsByName('region');
        var defaultRegion = null;
        for (var i = 0; i < regions.length; i++) {
          regions[i].addEventListener('click', drawChart, false);
          if (regions[i].checked) {
            defaultRegion = regions[i];
            //console.log(regions[i]);
          }
        }
        if ((defaultRegion === null) && (regions.length > 0)) {
          defaultRegion = regions[0];
          defaultRegion.checked = true;
        }
        drawChart({
          target: defaultRegion
        });
        //console.log(drawChart);

        // radio on 'click' handler
        function drawChart(sender) {
          options1.region = null;
          if (sender.target.value !== 'all') {
            options1.region = sender.target.value;
            //console.log(sender.target.value);
          }
          chart1.draw(view1, options1);
        }

      }

      function drawRegionsMap() {
        var query1 = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1ysbR58fP12YRfrvWtYoJRrLnbCwooR7kTjVldz-pWJc/edit?usp=sharing");
        query1.setQuery('select * where N = "Y" and G="WEEE" and O="Country" and H="Take back policy model"');
        //bat sheet
        var query2 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1ysbR58fP12YRfrvWtYoJRrLnbCwooR7kTjVldz-pWJc/edit?usp=sharing');
        query2.setQuery('select * where N="Y" and G="Batteries" and O="Country" and H="Take back policy model"');
        //pack sheet
        var query3 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1ysbR58fP12YRfrvWtYoJRrLnbCwooR7kTjVldz-pWJc/edit?usp=sharing');
        query3.setQuery('select * where N="Y" and G="Packaging" and O="Country" and H="Take back policy model"');

        query1.send(function (response) {
          handleQueryResponseTR(response, 'colormap1');
        });
        query2.send(function (response) {
          handleQueryResponseTR(response, 'colormap2');
        });
        query3.send(function (response) {
          handleQueryResponseTR(response, 'colormap3');
        });
      }

    </script>


    <div class="content">

      <div id="chartwithoverlay1">
        <div id="overlay1">WEEE</div>
        <div id="regionbutton">
          <div id="radio1"><input type="radio" name="region" id="all" value="all" /><label for="all">All</label></div>
          <div id="radio2"><input type="radio" name="region" id="africa" value="002" /><label for="africa">Africa</label></div>

          <div id="radio4"><input type="radio" name="region" id="americas" value="013" /><label for="americas">Central America</label></div>
          <div id="radio5"><input type="radio" name="region" id="americas" value="005" /><label for="americas">South America</label></div>
          <div id="radio6"><input type="radio" name="region" id="europe" value="150" /><label for="europe">Europe</label></div>
          <div id="radio7"><input type="radio" name="region" id="asia" value="142" /><label for="asia">Asia/Middle East</label></div>
        </div>
        <div id='colormap1'> </div>
      </div>

      <div id="chartwithoverlay2">
        <div id="overlay2">Batteries</div>
        <div id='colormap2'> </div>
      </div>

      <div id="chartwithoverlay3">
        <div id="overlay3">Packaging</div>
        <div id='colormap3'> </div>
      </div>
      <div id="img">
        <img src="legend.png" alt="" />
      </div>
    </div>
    <div class="preload">
      <img src="http://i.imgur.com/KUJoe.gif">
    </div>
  </body>

</html>