Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get single item firebase

I am beginning with queries in Firebase database, and will love some more insights.

This query works in retrieving a single item from the firebase database. My understanding inline.

  var ref = DatabaseRef; // root of my fbase db
  var codeRef = ref.child('codes'); // at root/codes/ now

  codeRef
    .child($stateParams.codeId) // a param comes in
    // grab value one-time 
    // https://www.firebase.com/docs/web/guide/retrieving-data.html#section-reading-once
    .once('value', function(snap) {
      console.log(snap.val());
    })

The above works. However below doesn't, and why? My understanding inline.

// same ref from above
codeRef
  // traverse the /codes/ url, and find all items that match
  // the specified param
  .equalTo($stateParams.codeId)
    .once('value', function(snap) {
      console.log(snap.val()); // returns `null`
    })

Instead, I expected all items matching to that id to show up. In this case, the id is unique, thus, I expected to get a single item back. However, a null is returned.

From the docs:

The equalTo() method allows us to filter based on exact matches. As is the case with the other range queries, it will fire for each matching child node.

So, maybe I'm seeing this whole Firebase Queries wrong. Will love to be enlightened.

like image 554
KhoPhi Avatar asked Dec 03 '25 17:12

KhoPhi


1 Answers

I am guessing that your data structure is as follows:

"codes" : {
        "codeId": {
            ....: ....
            }
        }

and you are querying against "codeId".

I would recomment adding codeId (key/value) under "codeId" object to query against, as follows:

"codes" : {
        "-yabba_dabba_doo": { // codeId 
            codeId : "-yabba_dabba_doo"
            }
        }

Now you can do this:

ref.child('codes').orderByChild('codeId').equalTo('-yabba_dabba_doo')

if I haven't guessed your data hierarchy correctly, then please share your firebase data hierarchy in order to help you.

like image 129
ALI MAKEEN Avatar answered Dec 07 '25 20:12

ALI MAKEEN