firebase retrieve data by using orderByKey() and equalTo()

前端 未结 2 1931
长发绾君心
长发绾君心 2021-02-03 13:03

So I\'m trying to find the data \"aaaaabbbbbbaaaa\" in this structure:

disney
 studentList
 -Jh46tlaNFx_YmgA8iMJ: \"aaaaabbbbbbaaaa\"
 -Jh474kAvoekE4hC7W3b:\"54c         


        
相关标签:
2条回答
  • 2021-02-03 13:48

    I guess it was added after your question was made, the solution here https://firebase.google.com/docs/database/admin/retrieve-data?hl=en#ordering-by-value tackles your need right away:

    ref("studentList").orderByValue().on("value", function(snapshot) {
      snapshot.forEach(function(data) {
        console.log(data.val());
      });
    });
    
    0 讨论(0)
  • 2021-02-03 13:49

    In the data sample that you've given, there is no node under studenList with a key of 54ca2c11d1afc1612871624a.

    Your keys are -Jh46tlaNFx_YmgA8iMJ and -Jh474kAvoekE4hC7W3b. You can easily determine this yourself by:

    ref.child("studentList").orderByKey().on("child_added", function(snapshot) {
      console.log(snapshot.key()); // on newer SDKs, this may be snapshot.key
    });
    

    You seem to want to order the nodes by their value, but that is not an operation that is available on Firebase at the moment. Firebase can only query children by a value of a named property, the key or its priority. So if you'd change the data structure to:

    disney
     studentList
       -Jh46tlaNFx_YmgA8iMJ:
         name: "aaaaabbbbbbaaaa"
       -Jh474kAvoekE4hC7W3b:
         name: "54ce1cbec4335cd3186105dc"
    

    You could get the children order by name with:

    ref.child("studentList")
       .orderByChild("name")
       .equalTo("54ca2c11d1afc1612871624a")
       .on("child_added", function(snapshot) {
          console.log(snapshot.val());
        });
    

    Just a side node: if your actual node values are like the ones in the sample you provided, you might want to consider using the values as the keys; they already seem pretty unique to my untrained eye.

    0 讨论(0)
提交回复
热议问题