内部数组值的Firebase查询

时间:2018-03-11 17:50:18

标签: javascript typescript firebase ionic-framework firebase-realtime-database

通过从我的应用程序的下拉列表中选择一个值,我需要获得一个包含其内部节点中所选值的每个Object的列表' foodtype'。

我的Firebase数据库中有以下结构:

restaurants
  - key: "12345"
    - name: "Salad house"
    - address: "Etc etc etc"
    - foodtypes
        - 0: "Salad"
        - 1: "Fastfood"
        - 2: "Seafood"
...

例如:如果我选择"沙拉","快餐"或"海鲜"我应该在我的餐馆列表中找到上面的对象。但是,如果我选择"日本食品"我不应该(或任何其他包含该记录的记录)。

有没有办法在Firebase中执行此操作而不创建大量的连接字段/值?我真的很感激任何建议!

1 个答案:

答案 0 :(得分:1)

这可以通过Cloud Firestore查询,而不是Firebase RTDB(实时数据库)查询。

如果您想使用Firebase RTDB进行处理,您的数据库应如下所示。

restaurants
  - key: "12345"
    - name: "Salad house"
    - address: "Etc etc etc"
    - foodtype: 0 (or 1 or 2 ...)
...

你也可以使用像“沙拉”,“快餐”,“海鲜”之类的字符串,但由于将来可以更改名称,我会使用整数作为常量变量,并在你的javascript代码中将其定义为{{1} },const FOODTYPE_SALAD = 0

最后,您可以获得以下代码列表。

const FOODTYPE_FASTFOOD = 1

但这种方式有一些缺点。

例如,您无法根据需要对列表进行排序。如果您想将餐馆列表排序为注册日期怎么办?

因此,在这种情况下,Firebase RTDB的最佳选项是对数据库进行非规范化并使数据库变平。

您需要Server side Fan-out on Cloud Functions for Firebase

这是数据库表的最终外观。

return restaurantsRef.orderByChild('foodtype').equalTo(FOODTYPE_SALAD).once('value').then(snap => {
    // TODO: ...
});

请记住,restaurants - key: "12345" - name: "Salad house" - address: "Etc etc etc" - foodtype: 0 - key: "22222" - name: "Fastfood house" - address: "Etc etc etc" - foodtype: 1 - key: "33333" - name: "Seafood house" - address: "Etc etc etc" - foodtype: 2 restaurants-salad - key: "12345" - name: "Salad house" - address: "Etc etc etc" - foodtype: 0 restaurants-fastfood - key: "22222" - name: "Fastfood house" - address: "Etc etc etc" - foodtype: 1 restaurants-seafood - key: "33333" - name: "Seafood house" - address: "Etc etc etc" - foodtype: 2 ... 应包含所有原始restaurants对象数据。