首页 > 解决方案 > Firebase orderByChild 没有重复数据

问题描述

我正在尝试对 Firebase 数据进行排序和显示,但是我被卡住了。我的数据库如下所示:

在此处输入图像描述

我需要对数据进行排序nr_of_matches,我可以通过这样的查询来做到这一点:

      const ref = firebase.database().ref('Matches/'+db_name).orderByChild('nr_of_matches')

      ref.once('value', function (snapshot) {
      snapshot.forEach(function (childSnapshot) {
      const matches = childSnapshot.val().matches
      const nr_of_matches = childSnapshot.val().nr_of_matches
      const the_matched = childSnapshot.val().the_matched
      console.log("matches : "+matches)

    });
    });

但是,我像这样检索重复的数据。为了不得到重复的数据,我可以这样做:

      const ref = firebase.database().ref('Matches/'+db_name+"/"+child.key).orderByChild('nr_of_matches')

      ref.on('value', function (snapshot) {
      const matches = snapshot.val().matches
      const nr_of_matches = snapshot.val().nr_of_matches
      const the_matched = snapshot.val().the_matched
      console.log("matches : "+matches)

    });

但后来它不再排序了。知道如何解决这个问题吗?

标签: javascriptfirebasefirebase-realtime-database

解决方案


如果您不想检索重复的数据,那么您可以使用query

      const ref = firebase.database().ref('Matches/'+db_name+"/").orderByChild('nr_of_matches').equalto(2);

      ref.on('value', function (snapshot) {
      const matches = snapshot.val().matches
      const nr_of_matches = snapshot.val().nr_of_matches
      const the_matched = snapshot.val().the_matched
      console.log("matches : "+matches)

    });

推荐阅读