【问题标题】:Removing data from Firebase Realtime Database removes all the data in the parent node从 Firebase 实时数据库中移除数据会移除父节点中的所有数据
【发布时间】:2020-01-06 23:24:19
【问题描述】:

我正在使用 Firebase 并正在编写代码以从实时数据库中删除数据。 我要做的是在单击按钮时从用户的书签部分中删除已保存的帖子,这是代码的关键部分:

let user=firebase.auth().currentUser;
var ref1=firebase.database().ref('saved/'+user.uid+'/posts/').orderByChild('postnum').equalTo(j); //j is the postnum of the post to be deleted
ref1.once('value',function(snapshot){
    snapshot.ref.remove();
});

代码不会删除有关特定帖子的信息,而是清除用户之前保存的所有帖子。 (即,这将清除 'saved/user.uid/posts/' 目录中的所有数据。

我做错了什么?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果列表。

    所以snapshot 变量包含一个结果列表。 snapshot.ref 指的是您运行查询的位置。因此,当您执行 snapshot.ref.delete() 时,您将删除运行查询的整个位置,而不仅仅是结果。

    要删除结果,遍历snapshot的子节点,一一删除:

    let user=firebase.auth().currentUser;
    var ref1=firebase.database().ref('saved/'+user.uid+'/posts/').orderByChild('postnum').equalTo(j); //j is the postnum of the post to be deleted
    ref1.once('value',function(snapshot){
      snapshot.forEach(function(child) {
        child.ref.remove();
      });
    });
    

    您还可以在循环后通过多位置更新一次性删除它们:

    let user=firebase.auth().currentUser;
    var ref1=firebase.database().ref('saved/'+user.uid+'/posts/').orderByChild('postnum').equalTo(j); //j is the postnum of the post to be deleted
    ref1.once('value',function(snapshot){
      let updates = [];
      snapshot.forEach(function(child) {
        updates[child.key] = null;
      });
      ref1.update(updates);
    });
    
    

    【讨论】:

    • 非常感谢!我应用了第一个代码,它运行良好。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2021-06-04
    • 1970-01-01
    • 2017-06-30
    • 2020-01-17
    • 2018-04-12
    相关资源
    最近更新 更多