0
votes

So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.

Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.

The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.

So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):

var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();

Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:

https://#mydatabaseurlhere.firebaseio.com/users/uid/chars

Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.

I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).

Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.

1

1 Answers

1
votes

You're defining a query. But that doesn't yet retrieve the data.

To retrieve the data, you need to attach a listener. For example:

var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();

getChar.on('value', function(snapshot) {
    snapshot.forEach(function(child) {
        console.log(child.key, child.val());
    });
});