Firebase how to find child knowing its id but not its parent's id (js)

旧街凉风 提交于 2019-12-13 04:26:48

问题


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

回答1:


You could put your reference to users first: var ref = firebase.database().ref('users');

Then loop through:

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



回答2:


Found the solution, if someone should encounter the same issue:

ref.once("value", function(snapshot) {
      snapshot.forEach(function(data) {
        snap = data.child(<YOUR_LIST_ID>).child('c').val();
        if (snap != null){
          myContent = snap;
        }
      });
});

also ref contrary to what everyone says has to be:

var ref = firebase.database().ref().child('users');

this doesn't work:

var ref = firebase.database().ref('users');


来源:https://stackoverflow.com/questions/52782070/firebase-how-to-find-child-knowing-its-id-but-not-its-parents-id-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!