我想用两个参数查询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);
答案 0 :(得分:1)
您已经注意到“您应该为每个OR条件创建一个单独的查询,并将查询结果合并到您的应用中”。由于在您的数据模型中,您有4个字段(animal1
至animal4
),因此您需要为要测试的每个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);