1
  1. My Sample Data

Sample firebase data

  1. Code

          let users_ref = firebase_instance.database().ref('users');
    
      let amount_of_data = 4;
      let limit_users_ref = users_ref.orderByChild("score").limitToLast(amount_of_data);
    
      limit_users_ref.once('value', function(snapshot) {
    
    
        snapshot.forEach(function(childSnapshot) {
    
          var childKey = childSnapshot.key;
          var childData = childSnapshot.val();
    
          console.log([childKey, childData]);
        });
    
    
      })
    
  2. Output I am getting

    Output result

As it can be seen on output, the data is not ordered. I should be getting test1 in stead of test3 there. Anything I am doing wrong?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ashik72
  • 153
  • 2
  • 9
  • 1
    As Doug answered, you're storing your numerical values as strings, so Firebase does a lexicographical sort. And in lexicographical ordering `"2"`, comes before `"10"`, just like `"aap"` comes before `"n"`. See https://stackoverflow.com/a/52732340/209103, https://stackoverflow.com/a/44762297/209103, https://stackoverflow.com/questions/37174300/firebase-query-ordering-not-working-properly/37192471#37192471 – Frank van Puffelen Feb 28 '19 at 00:29

1 Answers1

2

Your scores are strings. They should be numbers instead. Strings don't sort like numbers.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441