Firebase - Retrieving Node using 'Node-Id'

By : senty
Source: Stackoverflow.com
Question!

I am having difficulties understanding how to use where while retrieving a full node. If I have a structure like:

- users
   -user_id1
      - key1:value1
      - key2:value2
   -user_id2
      - key1:value3
      - key2:value4
  ...

If I know "user_id1", how can I get the whole node; so I can use snapshot.key to get the user_id, and use snapshot.value to get as [key:value]?

   -user_id1
      - key1:value1
      - key2:value2

This is what I tried so far...

let key = "user_id1"   // static for test

let usersRef = Firebase(url: secret + "/users")
usersRef.queryEqualToValue(key).observeSingleEventOfType(.Value, withBlock: { snapshot in

       print(snapshot)

//     print(snapshot.key)   // id
//     print(snapshot.value) // [key:value]                  
})

This is returning:

Snap (users) <null>

Snap (users) <null>

By : senty


Answers

Try adding queryOrderedByKey()

For example

let ref = root.child("users")

ref.queryOrderedByKey().queryEqualToValue("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in

    // could get many items in snapshot hence the loop

    for item in snapshot.children {
        print(item)
    }

})
By : DogCoffee


It's a lot simpler than what you're trying:

ref.child("users").child("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
    print(item.key)
    print(item.value)
})

This is not just simpler, it's also cheaper for the database, since it doesn't have to perform a (potentially expensive) query.

For an example, see this section of the documentation on reading child value with Swift.



This video can help you solving your question :)
By: admin