分开的查询,而不是Firestore中的多个where子句

时间:2018-10-28 14:29:26

标签: javascript node.js firebase nosql google-cloud-firestore

我想用两个参数查询Firebase Firestore数据收集。

集合:动物

"animals": {
   "1": {
      "animal1": "cat",
      "animal2": "dog",
      "animal3": "",
      "animal4": ""
   },
   "2": {
      "animal1": "dog",
      "animal2": "cat",
      "animal3": "",
      "animal4": ""
   },
   "3": {
      "animal1": "cat",
      "animal2": "bird",
      "animal3": "dog",
      "animal4": ""
   },
   "4": {
      "animal1": "wolf",
      "animal2": "dog",
      "animal3": "bird",
      "animal4": ""
   },
   "5": {
      "animal1": "turtle",
      "animal2": "dog",
      "animal3": "wolf",
      "animal4": "cat"
   },
   "6": {
      "animal1": "dog",
      "animal2": "wolf",
      "animal3": "turtle",
      "animal4": "bear"
   },
   "7": {
      "animal1": "spider",
      "animal2": "beatle",
      "animal3": "butterfly",
      "animal4": "Cat"
   }
}

我想获取包含的列表数据。 有信息In here 逻辑或查询。在这种情况下,您应该为每个OR条件创建一个单独的查询,然后将查询结果合并到您的应用中。

我不知道我需要多少个单独的查询?

let param1 = 'cat';
let param2 = 'dog';

let query1 = db.collection('animals').where('animal1', '==', param1);
let query2 = db.collection('animals').where('animal2', '==', param1);
let query3 = db.collection('animals').where('animal3', '==', param2);
let query4 = db.collection('animals').where('animal4', '==', param3);

1 个答案:

答案 0 :(得分:1)

您已经注意到“您应该为每个OR条件创建一个单独的查询,并将查询结果合并到您的应用中”。由于在您的数据模型中,您有4个字段(animal1animal4),因此您需要为要测试的每个param值创建4个查询。

因此,对于2个参数,如下所示:

let param1 = 'cat';
let param2 = 'dog';

您将不得不合并2 * 4查询的结果。...

如果您更改数据模型并使用数组存储animal值,则可以减少此数字。然后,您可以利用array_contains运算符。

建议的数据模型:

"animals": {
   "1": {
      "animalArray": 
          [
             0: "cat",
             1: "dog"
          ] 
   },
   "2": {
      "animalArray": 
          [
             0: "turtle",
             1: "dog",
             2: "wolf",
             3: "bear",
          ]
   }
   .....
}

在我们有两个params的示例中,您只需要两个查询,如下所示:

let query1 = db.collection('animals').where("animalArray", "array-contains", param1);
let query2 = db.collection('animals').where("animalArray", "array-contains", param2);