首页 > 解决方案 > Firebase how to find child knowing its id but not its parent's id (js)

问题描述

I have a firebase realtime database (not cloud) structure like:

users
  kasdf872ajsda   //user id
     auiiq6d182g1   //list id
        c: <mycontent>   //list content

i know the list id (in this case auiiq6d182g1) and i want to retrieve <mycontent>, but i don't know the user id kasdf872ajsda , because what i'm going to retrieve is probably not from the user currently using the website (and i'm not setting any database rules for "read" in fact, only for "write" is that correct?).

What i'm doing right now is this (not working):

var ref = firebase.database().ref().child('users');
ref.child(listID).once("value", function(snapshot) {
  var snap = snapshot.val();
  myContent = snap.c;
});

标签: javascriptdatabasefirebasesnapshot

解决方案


您可以先参考用户:var ref = firebase.database().ref('users');

然后循环:

ref.once('value').then((snapshot)=>{
   snapshot.forEach(function(data) {
      if (data.key == <YOUR_LIST_ID>) {
         //you can access data.c here...
      }
  });
});  

推荐阅读