Gaston Levy Mayo
Gaston Levy Mayo

Reputation: 25

Firebase orderByKey().startAt() not working as expected. What's wrong?

I'm trying to get firebase data from a node which uid must start with a passed string.

I tried a code but I always get the same data. The database data is as following:

enter image description here

And I'm using the following code:

var ref = firebase.database().ref("restaurantes/history");
    ref.orderByKey().startAt(userUID).once("child_added", function(snapshot) {
      snapshot.forEach(child => {
        if(child.key == "orders")
        {
          console.log(child.val());

          _.each(child.val(), (value, key) => {
            arrtmp.push(value)
          })
        }    

      })

If user is "FKQLlqa" I should get the history data shown in the picture. If I user is "abc" I shouldn't get any data. But I always get the data shown in the picture. Should I use another way of querying? Or I should use a key field inside orders and payments data?

Regards!

Upvotes: 1

Views: 966

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Peter's answer is the correct solution. I'm merely adding this for completeness.

When you call orderBy... on a Firebase reference, the database orders all child nodes on the key/value/child that you specify.

If you then subsequently call startAt(...) on the query, it finds the (first) node that starts with that value and starts returning all results from there. So if you start at FKQLlqa, it will start returning keys at FKQLlqa and then return all keys after it.

If you want to return the child node(s) with a specific key/value/child, you'd use equalTo(...). So:

ref.orderByKey().equalTo(userUID).once("child_added", function(snapshot) {
  ... 

But as Peter said already, this is just a more expensive way to look up a child with a known key. I highly recommend using his better approach: ref.child(userUID).once("value".

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80914

Try the following:

var ref = firebase.database().ref("restaurantes/history");
ref.child(userUID).once("value", function(snapshot) {
  if (snapshot.exists()) {
      console.log(snapshot.val());
    }
  else {
      console.log("different user");    
  });

This will check if the snapshot that contains the userId (added as a parameter in the child() method), already exists in the database then you will be able to retrieve the data under the userId.

For reference:

https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists

Upvotes: 2

Related Questions