Search elements object with specific key value in firebase database

ぃ、小莉子 提交于 2019-12-23 12:08:30

问题


I am trying to search with specific value with of userkey in firebase database but i am getting below issues.

I want to fetch like if i pass user key 11112 then two records will come when i pass 11113 then one record will come.

Even though I have tried with below code but getting error. firebase script :-

 <script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.15/firebase.js'></script>

Code:

var ref = new Firebase('fire-base-url');
ref.orderBy("userkey").equalTo("11112").once("value", function(snapshot) {
  console.log(snapshot.key);
});

Console Error:

Uncaught TypeError: ref.orderBy is not a function

回答1:


There is two problems with your code.

  1. As @theblindprophet already mentioned, you should be using orderByChild instead of orderBy.
  2. You are using the old firebase SDK. It won't work with applications created in the new firebase console.

    Please make sure to use the new 3.1 firebase sdk with

    <script type='text/javascript' src='https://www.gstatic.com/firebasejs/3.1.0/firebase.js'></script>
    

    Then you should initialize your app using

      var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
      };
      firebase.initializeApp(config);
    

    You will be able to get your config details by going to the console, clicking in your application name and pressing Add Firebase to your Web app.

    Then to get your ref object you will need the code bellow.

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

Take a look in this jsFiddle to see a full working example.




回答2:


Your error:

Uncaught TypeError: ref.orderBy is not a function

is telling it can't find the function orderBy and that is because it doesn't exist.

You are looking for orderByChild.

var ref = new Firebase('fire-base-url');
ref.orderByChild("userkey").equalTo("11112").once("value", function(snapshot) {
    console.log(snapshot.key);
});

Reference: orderByChild and equalTo




回答3:


Grab a snapshot of the uid values. Then compare userkey with the search parameter you pass in.

var rootRef = new Firebase('fire-base-url');
var userRef = rootRef.child(user.uid);
userRef.on('value', function(snapshot){
  var myDbKey = snapshot.child("userkey");
  if (mySearchKey === myDbKey) {
    ...
  }
});


来源:https://stackoverflow.com/questions/38590303/search-elements-object-with-specific-key-value-in-firebase-database

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