bigpotato
bigpotato

Reputation: 27507

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???

Upvotes: 11

Views: 18453

Answers (3)

Ramah
Ramah

Reputation: 86

How about

const location = database.ref('locations/050PNS74ZW8XZ');

Upvotes: 0

cartant
cartant

Reputation: 58400

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.

Upvotes: 15

Niles Tanner
Niles Tanner

Reputation: 4021

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.

Upvotes: 2

Related Questions