sbhatt
sbhatt

Reputation: 411

Firebase reading a particular key values

Basically I have my username as a key for user data. Now I am trying to match the username with my current username stored in session storage and read the userdata for that username.

Here is my .js code

var database = firebase.database();
var currentusername = sessionStorage.getItem("username");
var userref = database.ref("users");

  userref.orderByChild("username").equalTo(currentusername).once("value").then(function(snapshot) {
        console.log(snapshot.val());
 });

Firebase Data Structure

Appname

When I try to run the above code I am getting snapshot.val() as null although there exists a record with a matching username key.

Upvotes: 1

Views: 105

Answers (2)

Ronnie Smith
Ronnie Smith

Reputation: 18585

This should work

var currentusername;
try {
    currentusername = sessionStorage.getItem("username");    
}
catch(error) {
    console.log("shucks " + error);
}

if(currentusername){
firebase.database().ref("users").child(currentusername).once('value').then(function(snap) {
        if(snap.val()){
            console.log(snap.val().firstname);
        }
    }, function(error) {
        // The Promise was rejected.
        console.log('Error: ',error);
    }); 
}  

Upvotes: 2

sbhatt
sbhatt

Reputation: 411

var userref = database.ref("users/"+currentusername);

    userref.once("value").then(function(snapshot)

This worked!!!

Upvotes: 4

Related Questions