Search code examples
javascriptfirebasefirebase-realtime-database

Firebase update child Javascript


I want to update child status as Active, but I really do not know how to solve this. I want to update a specific record, I am using table btw. I'm stuck here already. Please help me. Thank you!

<script>
  // Get a reference to the database service
  var database = firebase.database();

  database.ref('Users').orderByChild('usertype').equalTo('Property Owner').on('value', function(snapshot) {
    if (snapshot.exists()) {
      var content = '';
      snapshot.forEach(function(data) {

        var stat = data.val();
        if (stat.status == 'Inactive') {
          var val = data.val();
          content += '<tr>';
          content += '<td>' + val.fname + '</td>';
          content += '<td>' + val.mname + '</td>';
          content += '<td>' + val.lname + '</td>';
          content += '<td>' + val.email + '</td>';
          content += '<td>' + val.registered + '</td>';
          content += '<td>' + val.status + '</td>';
          content += '<td><button type="button" id="button" style="font-size: 12px;class="btn btn-danger" onclick="myFunction()">Update Status</button></td>';
          content += '</tr>';

        }
      });
    }
    $('#ex-table').append(content);
  });

  function myFunction() {
    alert('');
  }
</script>

This is my json tree in firebase.


Solution

  • Ok, let me take a crack at this, what you're trying to do is update a field. You can find info in the docs on how to do so here, but essentially what you need to do is build a reference to the specific user you want to modify, and then call update on it. So, in whatever you have listening to the button, you want to do something like

    firebase.database().ref().update({'users/USERNAME/status': "Active"})
    

    Where USERNAME is the name of the specific user you want to update.