Firebase查询从数据库中删除特定值

时间:2018-01-19 11:55:30

标签: javascript json firebase firebase-realtime-database

我在firebase上有这些数据:

transportation: {
"car" : {
    "bus" : {
      "toyota" : false,
      "bmw" : true
    },
    "suv" : {
      "honda" : false,
      "toyota" : true,
    }
  }
}

我想删除所有包含“false”值数据的子项,以便我的数据如下所示:

transportation: {
    "car" : {
        "bus" : {

          "bmw" : true
        },
        "suv" : {

          "toyota" : true,
        }
      }
    }

3 个答案:

答案 0 :(得分:1)

这是代码,

  var ref = firebase.database().ref().child('transportation/')
   ref.once("value")
  .then(function(snapshot) {
  data = snapshot.val();
        for (var i=0;i < Object.keys(data).length;i++){
            Object.keys(data)[i].forEach(function(childSnapshot) {
              if(childSnapshot.val() == "false"){
                  childSnapshot.ref.remove();
                }
              });
        }
  }).catch(function(error) {alert("Data could not be deleted." + error);}););

答案 1 :(得分:0)

为了从fairbase删除其值的记录,bellow可能会起作用:

var dB = firebase.database()
dB.ref('transportation/car').once('value', snap={
     snap.forEach(s =>{
        var obj =s.val();
        var keys = s.key;
          for (var key in obj ) {
            if (!obj[key]) {
               // In order to delete:  set the path null
               dB.ref('transportation/car/' + keys + "/" + key).set(null);
            }   
          }

    }); 
});

答案 2 :(得分:0)

删除具有false的特定值的数据。我们需要获取节点的所有数据,然后使用键来映射数据,以使用值为false的对象的精确值来删除数据。

let transportationRef = firebase.database().ref().child('transportation/')
  transportationRef.child("car").once('value', s => {
    if (s.exists()) {
      // map through objects returned from transportationRef and map through the objects
      Object.keys(s.val()).map(k => {
          // deleting the node which contains `false` as value
          if(s.val()[k]=="false"){
            s.ref.remove()
          }
      })
    }
})