简体   繁体   中英

How to find parent key using child key in firebase realtime-database?

In firebase realtime-database, my project have a structure like below:

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

How could i find user_id by post_id?

I have searched that before but i could not find an appropriate solution for my case. If there is any i missed out, please report me and i would be thankful for you.

I have tried to use orderByKey() and orderByChild() methods but they did not helped me to handle this problem. At the end, i was able to find the wanted user_id using a logic below:

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);
});

As it is seen, that is not a best way to find user_id because the method loads lots of data in the client side.

So, how can i find user_id using firebase query methods or any other method, when i only know post_id?

One work around can be you can save user_id in post_id node

  • posts
    • user_id
      • post_id
        • post_content = "..."
        • date =...
        • user_id = #id...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM