2

I am trying to get the key from a child nodes data.

$(document).on('click', '#enter', getName);

function getName() {

    name = $('#user').val().trim();
    database.ref('players/' + name).push({
        name: name
    })
}

database.ref('players/' + name).child(name).on("child_added",
    function(childSnapshot){

        var childKey = childSnapshot.key;
        var childData = childSnapshot.val;
        console.log('key', childKey)
        console.log('data', childData)

    }, function (errorObject) {

        console.log("The read failed: " + errorObject.code);
    })
})

In the snapshot function, when I console log the childKey, it shows the key is the name of the user, which is the path I created in the ref('players/' + name). But I need the key for the node that gets nested inside the name node. I get an error in my childSnapshot function saying that the .child(name) is an invalid path. Also says,

Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"

Currently when I create data onto Firebase it looks like this:

-players
   -Johnson
     -KWH4mjWbOuptod_vV1o
        name: "ajks"

I need to get the key under johnson, that long string of letter and numbers so I can reference that specific node and add data, change data or update data such as the name.

cartant
  • 57,105
  • 17
  • 163
  • 197
H. Lee
  • 67
  • 1
  • 9
  • 3
    Possible duplicate of [In Firebase when using push() How do I pull the unique ID](http://stackoverflow.com/questions/16637035/in-firebase-when-using-push-how-do-i-pull-the-unique-id) – cartant Nov 11 '16 at 08:45

1 Answers1

2

Try this way

var fb_ref= firebase.database().ref('players/' + name)
fb_ref.push({
              name: name
})
fb_ref.on('child_added', function (data) {
                console.log(data.key);
            });

or

fb_ref.push({
              name: name
}).then(function(fb_ref){
   console.log(fb_ref.key);
})

Keep one thing in mind, if your using firebase version above 3.x means use "key", in case your version lesser than 3.x means use "key()" like this

MuruGan
  • 1,402
  • 2
  • 11
  • 23