Diaconu Eduard Diaconu Eduard - 5 months ago 39
AngularJS Question

Remove specific user from Firebase

I try to make a online database (Firebase), for test and learn.
I successfully added members in database, but i don't know where is the problem with my code from remove.

Here is my code:

<!DOCTYPE html>
<html>
<head>


</head>
<body>
<button onclick="saveData()">Save Data</button>
<button onclick="printData()">Print Data</button>
<button onclick="printData2()">Print Data2</button>
<button onclick="remove()">Remove</button>
<script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
<script>
var ref = new Firebase("https://projecttest-9aee9.firebaseio.com/web/saving-data/fireblog");
var usersRef = ref.child("users");
function saveData(){
usersRef.set({
alanisawesome: {
date_of_birth: "June 23, 1912",
full_name: "Alan Turing"
},
gracehop: {
date_of_birth: "December 9, 1906",
full_name: "Grace Hopper"
}
});
}

function printData(){

usersRef.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
function printData2(){

ref.child("users/gracehop/date_of_birth").on("value", function(snapshot) {
console.log(snapshot.val());//"December 9, 1906"
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
var ref = new Firebase("https://projecttest-9aee9.firebaseio.com/web/saving-data/fireblog/users");
var usersRef= ref.child("users");
function remove(){
usersRef.remove({

.then(function() {
console.log("Remove succeeded.")
})
.catch(function(error) {
console.log("Remove failed: " + error.message)
})
});
}
</script>
</body>
</html>


I'm novice and i need your help!

Thank you for interest!

Answer

The syntax of remove() is wrong, promises are handled like this:

usersRef.remove()
  .then(function() {
    console.log("Remove succeeded.")
  })
  .catch(function(error) {
    console.log("Remove failed: " + error.message)
  });

When that's fixed, you need to make sure usersRef corresponds to what you want to delete.

If your users are keyed by Firebase users ids, for example:

 "users" : {
    "8dGTb3sxVCbll" : {
      ...
    },
    "bGIav9o7PhhIB" : {
      ...
    },  
 }

you want to set userRef to something like this

usersRef = firebase.database().ref(`users/${user.uid}`);

And then simply do

usersRef.remove()

There is also a possibly cleaner way of deleting a user. From the docs

var user = firebase.auth().currentUser;

user.delete().then(function() {
  // User deleted.
}, function(error) {
  // An error happened.
});

I don't know exactly your setup, so you may need to try both solutions. Let me know if you have questions.