Order by value in Firebase Realtime Database

I want to order by the value of posicion the products objects:

{
  "categorias" : {
    "productos" : {
      "0001-0001" : {
        "numero" : "0001-0001",
        "posicion" : 10
      },
      "0001-0002" : {
        "numero" : "0001-0002",
        "posicion" : 20
      },
      "0001-0003" : {
        "numero" : "0001-0003",
        "posicion" : 30
      },
      "0001-0004" : {
        "numero" : "0001-0004",
        "posicion" : 40
      },
      "0001-0005" : {
        "numero" : "0001-0005",
        "posicion" : 50
      },
      "0001-0006" : {
        "numero" : "0001-0006",
        "posicion" : 60
      }
    }
  }
}

I have read the firebase documentation but there is no example of this, there are only examples of orderByKey and orderByChild.

I would be very grateful if someone could help me. Thanks

Answer

You can try the following code, it sorts the children in “productos” node based on the value of “posicion”.

const db = firebase.database()
db.ref("categorias/productos").orderByChild("posicion").once("value").then((list) => {
  list.forEach((product) => {
    console.log(product.val())
  })
})

I tried it out with your sample JSON and here’s the output: enter image description here

orderByChild() sorts it in ascending order. If you need the list in descending order then you would have to do it using Javascript yourself.

PS: Please do not use console.log(list.val()) directly as then the object won’t appear to be sorted because your browser may reorder the keys of object in alphabetical order.

Therefore you should ideally run a forEach loop on the snapshot (list in this case).