2016-07-08 69 views
0

我尝试制作在线数据库(Firebase),以便测试和学习。 我成功地在数据库中添加了成员​​,但我不知道我的代码从删除的问题在哪里。从Firebase中移除特定用户

这里是我的代码:

<!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> 

我是新手,我需要你的帮助!

感谢您的关注!

回答

2

remove()的语法是错误的,承诺都是这样处理的:

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

当这是固定不变的,你需要确保usersRef对应要删除的内容。

如果你的用户是通过火力地堡用户的id键,例如:

"users" : { 
    "8dGTb3sxVCbll" : { 
     ... 
    }, 
    "bGIav9o7PhhIB" : { 
     ... 
    }, 
} 
要设置 userRef到这样的事情

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

,然后简单地做

usersRef.remove() 

还有一种可能更简洁的删除用户的方式。从the docs

var user = firebase.auth().currentUser; 

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

我并不确切地知道你的设置,所以你可能需要尝试这两种解决方案。 如果您有任何疑问,请告诉我。

相关问题