Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: How to query by key?

I have a locations table that I want to query. The key is "050PNS74ZW8XZ".

enter image description here

As you can see, it exists.

However, when I print out any attributes it doesn't work

function testing(req, resp) {
  const location = database.ref('locations').equalTo('050PNS74ZW8XZ');
  console.log('location:', location.account_capabilities); // <--- prints undefined
  resp.json("asfdsf");
}

What am I doing wrong???

like image 626
bigpotato Avatar asked Nov 07 '16 21:11

bigpotato


People also ask

What does getKey () do Firebase?

Calling the getKey() method on this reference will return the auto-generated key which may then be used to store a corresponding value. Using Firebase to generate unique keys in this way is also of particular use when an app has multiple users creating child nodes at the same path in the tree.

How do I get particular data from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

How do I find my Firebase key?

How do I get keys from Firebase? Firebase automatically creates API keys for your project when you do any of the following: Create a Firebase project > Browser key auto-created. Create a Firebase Apple App > iOS key auto-created. Create a Firebase Android App > Android key auto-created.


2 Answers

If you know the key, you can use the child method.

However, the more fundamental problem is that the value is not directly available from the ref. You can obtain the value using the once method - to listen for the value event - which returns a promise that resolves to a snapshot:

function testing(req, resp, next) {
  database.ref('locations').child('050PNS74ZW8XZ')
    .once('value')
    .then(function(snapshot) {
      var value = snapshot.val();
      console.log('location:', value.account_capabilities);
      resp.json(value.account_capabilities);
    })
    .catch(next);
}

There is more information in the documentation.

like image 78
cartant Avatar answered Oct 22 '22 11:10

cartant


if you know the key you can access the child directly, then turn it into a object with $firebaseObject.

var locref = database.ref('locations').child('050PNS74ZW8XZ');
const location = $firebaseObject(locref);

the equalTo function should be used when querying from a list.

like image 2
Niles Tanner Avatar answered Oct 22 '22 13:10

Niles Tanner