【问题标题】:How to find parent key using child key in firebase realtime-database?如何在firebase实时数据库中使用子键查找父键?
【发布时间】:2021-01-14 19:02:24
【问题描述】:

在 firebase 实时数据库中,我的项目具有如下结构:

- posts
    - user_id
        - post_id
            - post_content = "..."
            - date = ...
            ...

如何通过 post_id 找到 user_id?

我之前已经搜索过,但我找不到适合我的情况的解决方案。如果有什么遗漏的,请报告我,我会很感激你的。

我曾尝试使用 orderByKey() 和 orderByChild() 方法,但它们并没有帮助我处理这个问题。最后,我能够使用以下逻辑找到想要的 user_id:

firebase.database().ref("posts")
    .once("value", function(snapshot) {
        snapshot.forEach(function(snapshot1) {
            snapshot1.forEach(function(snapshot2) {
                if (snapshot2.toJSON().postId === "post_id") {
                    var topicID = snapshot1.key;
                    console.log(topicID);
                }
            });
        });
}, (e) => {
    console.log(e);
});

正如所见,这不是查找 user_id 的最佳方法,因为该方法会在客户端加载大量数据。

那么,当我只知道 post_id 时,如何使用 firebase 查询方法或任何其他方法找到 user_id?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    一种解决方法是您可以将 user_id 保存在 post_id 节点中

    • 帖子
      • user_id
        • post_id
          • post_content = "..."
          • 日期 = ...
          • user_id = #id ...

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多