使用AngularJS在Firebase实时数据库中使用.indexOn规则过滤数据

时间:2019-04-22 05:10:19

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

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

FireBase

{
  "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
    }
  }
}

1 个答案:

答案 0 :(得分: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对象中的数据顺序与服务器上的顺序相匹配”。