Home > Software design >  Getting highest score values from firebase database
Getting highest score values from firebase database

Time:01-02

In my website there are some films that i get from firebase. The scores of the movies are between 0 and 100. I already got all the movies in my website. I also want to display them in descending order.(for ex. top 5 rated movies) How can i achieve this? Thanks for your answers.

           const app = initializeApp(firebaseConfig);
           const db = getDatabase(app);
           const auth = getAuth(app);
           const firebaseRef= ref(getDatabase());
    
    
      var body = document.getElementById('movies');
      var body2 = document.getElementById('series');
    
    
    function AddItemsToTable(name, score, img, id) {
        var movies = `<div ><a href="movieDetail.html?movieId=${id}"><img src="${img}" ></a><p><a href="movieDetail.html?movieId=${id}">${name}</a></p> <p> <i  id="star${id}"></i>&nbsp;<a >${score}%</a> </p> </div>`;
        body.innerHTML =movies;
    
    }
    function AddItemsToTable2(name, score, img, id) {
        var series = `<div ><a href="seriesDetail.html?seriesId=${id}"><img src="${img}" ></a><p><a href="seriesDetail.html?seriesId=${id}">${name}</a></p> <p> <i  id="star2${id}"></i>&nbsp;<a >${score}%</a> </p> </div>`;
        body2.innerHTML  = series;
    
    }
    
    
    //*******************************I got the movies************************************************
            function AddAllItemsToTable(TheMovies){
              var counter=0;
                TheMovies.forEach(element => {
                  if (counter===6) {
                    return;
                  }
                    AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
                 
                    counter  ;
            });
          }
          //************************I got tv series*********************************************
          function AddAllItemsToTable2(TheSeries){
              var counter=0;
    
          TheSeries.forEach(element => {
            if (counter===6) {
              return;
            }
              AddItemsToTable2(element.seriesName, element.seriesScore, element.seriesImage, element.seriesId);
              counter  ;
    
      });
    
        }
        function AddAllItemsToTable3(TheMovies){
          var counter=0;
            TheMovies.forEach(element => {
              if (counter===6) {
                return;
              }
                AddItemsToTable3(element.movieName, element.movieScore, element.movieImage, element.movieId);
               
                counter  ;
        });
    
      }
    
            function getAllDataOnce(){
                const dbRef=ref(db);
                get(child(dbRef,"Movies"))
                        .then((snapshot)=>{
                            var movies=[];
                    snapshot.forEach(childSnapshot => {
                        movies.push(childSnapshot.val())
                    });
                    AddAllItemsToTable(movies);
                });
            }
            function getAllDataOnce2(){
                const dbRef=ref(db);
                get(child(dbRef,"Series"))
                        .then((snapshot)=>{
                            var series=[];
                    snapshot.forEach(childSnapshot => {
                        series.push(childSnapshot.val())
                    });
                    AddAllItemsToTable2(series);
    
                });
            }
    
    
                window.onload = (event) => {
                    getAllDataOnce();
                    getAllDataOnce2();
    };
      <div >

          <header >

              <div >
                <a href="main.html" style="logo" > <img src="img/sonlogo3.png" alt="logo"></a>
                <a href="main.html" style="logo"  > <img src="img/logosmall.png" alt="logo" style="width:60px;height:48px;margin:5px;"></a>


              </div>
              <div >
            <input type="text" placeholder="Movies or TV series.." ><i ></i>  </input>
                <ul>
                <li ><a href="#">Categories&nbsp;&nbsp;<i  style="font-size:16px;"> </i></a>
                 <ul >
                      <li><a href="series.html">TV Series</a></li>
                      <li><a href="movies.html">Movies</a></li>
                    </ul>
                </li>
                  </ul>
              </div>

              <div >

                <ul>
                  <li>
                  <button  type="button" data-toggle="dropdown"><i ></i>  </button>
                  <ul >
                   <li ><b><script>document.write(document.cookie.substring(5))</script></b></li>
                   <li ><a href="login.html" style="color:red;"><i  style="color:red;"></i>&nbsp;&nbsp;&nbsp;Login</a> </li>
                   <li ><a href="signup.html" style="color:red;"><i  style="color:red;"></i>&nbsp;&nbsp;Sign up</a> </li>
                   <li ><a onclick="deletecookie()" style="cursor:pointer;"><i  style="color:red;"></i>&nbsp;&nbsp;Log out</a></li>
                </ul>
                  </li>
                </ul>
              </div>
          </header>

          <div  id="body">

              <div >Movies</div>
              <div ><a href="movies.html">See all</a></div>
              <div id="movies">
              </div>

                <div >Series</div>
                <div ><a href="series.html">See all</a></div>
              <div id="series">
              </div>

              <div >Top Rated Movies</div>
              <div ><a href="#">See all</a></div>
              <div id="toprated">
              </div>



</div>
          <div >
              <div >
                  <img src="img/sonlogo3.png" alt="logo">
                  <ul>
                    <li><a href="#">Help</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Contact</a></li>
                    <li><a href="#">Terms and Policies</a></li>

                  </ul><br><br>
                  <ul>
                    <li>© 2021 Cinemeter</li>
                    <li >|</li>

                    <li>All rights reserved.</li>
                  </ul>
              </div>


          </div>
        </div>

Firebase Database enter image description here

This is my website enter image description here

CodePudding user response:

While Firebase can order results, the results are always ascending. If you want to show them in descending order, you'll have to reverse them in your application code.

Something like this:

const query = query(child(dbRef,"Movies"), orderByChild("movieScore"));
get(query).then((snapshot)=>{
    var movies=[];
    snapshot.forEach(childSnapshot => {
        movies.push(childSnapshot.val())
    });
    movies.reverse
});

If you want to get the top scores, you can use limitToLast in the query too:

const query = query(child(dbRef,"Movies"), orderByChild("movieScore"), limitToLast(5));

Also see the Firebase documentation on ordering and filtering data and limiting the number of results.

A few notes on your data structure:

  • Using sequential numeric keys for you nodes is an anti-pattern in Firebase, and it is typically better to use push keys. Also see Best Practices: Arrays in Firebase.
  • You're storing the score as a string, which is bound to lead to problems as strings are sorted lexicographically. I recommend converting your data to store the scores as numbers (so without " quotes around them).
  • Related