【问题标题】:Filter data with .indexOn rules in Firebase realtime database with AngularJS使用 AngularJS 在 Firebase 实时数据库中使用 .indexOn 规则过滤数据
【发布时间】:2019-09-11 08:26:13
【问题描述】:

我正在使用如下所示的 FireBase 实时数据库结构。并想提取所有具有red 颜色的model

火力基地

{
  "models": {
    "model1": {
      "modelName": "model 1",
      "color": {
        "red": true,
        "blue": true,
        "green": true
      }
    },
    "model2": {
      "modelName": "model 2",
      "color": {
        "yellow": true,
        "blue": true,
        "green": true
      }
    },
    "model3": {
      "modelName": "model 3",
      "color": {
        "red": true,
        "yellow": true,
        "pink": true
      }
    },
    "model4": {
      "modelName": "model 4",
      "color": {
        "red": true,
        "orange": true,
        "white": true
      }
    }
  }
}

我尝试使用下面的查询,但没有得到预期的结果。

AngularJS

let fbRef = firebase.database().ref('models');

fbRef
    .orderByChild('red')
    .equalTo(true)
    .once('value', function(data){
      console.log('result : ', data);
    });

FireBase 规则

{
  "rules": {
    ".read": true,

    "$modelID": {
      ".read": true,
      ".indexOn": ["red", "blue", "green", "orange", "pink", "white", "yellow"]
    }

  }
}

预期结果

{
  "model1": {
    "modelName": "model 1",
    "color": {
      "red": true,
      "blue": true,
      "green": true
    }
  },
  "model3": {
    "modelName": "model 3",
    "color": {
      "red": true,
      "yellow": true,
      "pink": true
    }
  },
  "model4": {
    "modelName": "model 4",
    "color": {
      "red": true,
      "orange": true,
      "white": true
    }
  }
}

【问题讨论】:

    标签: angular firebase ionic-framework firebase-realtime-database ionic4


    【解决方案1】:

    您应该通过'color/red'订购,如下:

      fbRef
        .orderByChild('color/red')
        .equalTo(true)
        .once('value', function(data) {
          //Use the val() method of the DataSnapshot
          console.log('result : ', data.val());
          //Or loop over children
          data.forEach(function(childSnapshot) {
            var childKey = childSnapshot.key;
            var childData = childSnapshot.val();
            console.log('childKey : ', childKey);
            console.log('childData : ', childData);
          });
        });
    

    由于您获得了DataSnapshot,您可以使用val() 方法将结果作为对象获取,或者使用forEach() 来“枚举DataSnapshot 中的顶级子项”。这两种方式的区别之一是“val() 返回的 JavaScript 对象中的数据排序不保证与服务器上的排序匹配”,如文档中所述。

    【讨论】:

    • 感谢@renaud-tarnec 的解决方案 .. 像魅力一样工作 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多