How to orderBy with Firebase and Javascript? - javascript

I'm trying to get data from Firebase Realtime Database with Javascript and order it by child's value.
I get the data, and limiting it works, but the order does not change.
Here is what I've tried:
var ref = database.ref('users').orderByChild('score').limitToLast(10);
Then I made score key with ".indexOn": "score" on firebase. Then I tried the following.
var ref = database.ref('users').orderByKey().limitToLast(10);[enter image description here][1]
I don't understand where I'm going wrong. I would really appreciate help!
Picture of firebase included!
firebase

It turned out that I had data in wrong format in firebase.
I had saved the score information as string so that's why orderBy did not give the wanted results.
After I changed the data in firebase the query worked just fine!

Related

In firebase (javascript), how can I get data for the currently logged in user?

I've spent a few days researching for the solution. I have found many answers that were quite helpful, but still I haven't been able to find a solution that fully resolved my problem. Basically all I want to do is to get current user's data (stored in firebase realtime database) and display them on the user's screen.
So far, I can display data for all the user. But how can I have it display data for only the current user? (How can I get the push key of only the current user?)
I'm not an experienced programmer (less than a year). Please use a language that is easy to understand.
I've gone through all the firebase documentation. Please don't just give me the copy of the documentation or the link to it.
Screenshot: Firebase realtime database
Screenshot: JavaScript function for retrieving current user's data
Additional JavaScript screenshot
User data is wherever you choose to store it--other than name, email, and a few other fields, the User object cannot actually store any other info. Therefore, you will need to decide where in the database you want to keep your extra data.
Assuming you choose to create a collection users with children named by uid, and you store the users' countries in those documents, the following will get you a specific user's data and you can use whatever fields you'd like from there:
let ref = database.ref('/users/' + currentUser.uid).once('value').then(function(snapshot) {
let userData = snapshot.val();
console.log(userData.country);
}
Here you go!
function showUser(){
var usref=firebase.database().ref("countries/"+uid);
//uid here is the unique code u gave to the specif user
usref.once('value', function(snapshot) {snapshot.forEach(function(childSnapshot) {
if((childSnapshot.key)=="country"){
var country = childSnapshot.val();
//use this variable here enter code here
window.alert(country);//just for checking!!!
}
if((childSnapshot.key)=="age"){
var name = childSnapshot.val();
//use this variable here
window.alert(name);//just for checking!!!
}
});
});
}
I hope this code works for you.

Firebase retrieves snapshot value as null

I use the .once( function in Firebase and am successfully retrieving the snapshot.key NAME of the directory. But this key has also a value.
When requesting snapshot.val() also gives out null despise it having a value.
The database looks like this:
stages {
stage1AVERYLONGHASH : "values i want to get"
stage2AVERYLONGHASH : "values i want to get"
}
My code
var ref = "stage1AVERYLONGHASH";
var branch = firebase.database().ref(ref).once('value').then(function(s){
console.log(s.key); // GIVES THE CORRECT ANSWER
console.log(s.val()); //GIVES null ... doesn't give me the "values i want.."
Am i doing it completely wrong?
I'm new to Firebase.
Please know that the database is structured like this intentionally.
I restricted read permission on "stages".
The game works as just requesting a hash from the database as a reference, to get contents.
I think you suppose to get the reference of the stage and then get the stage1 reference from him like :
.ref("stage").child("stage1")
I'm not sure about the actual syntax but I know that this is how I get my firebase data in android studio

Retrieving data from Firebase (web) not working

I just got into Firebase and I´m trying to retrieve data from the realtime database, but I can't get anything to show up on the webpage.
This is what I got, before the JS I got the initialize Firebase code. (IF I delete the val() I receive [object Object] so something is at least working).
JS:
var heading = document.getElementById("head");
var firebaseHeadingRef = firebase.database().ref().child("Heading");
firebaseHeadingRef.on('value', function(datasnapshot) {
heading.innerText = datasnapshot.val();
});
HTML:
<div id="table_body"> <h1 id="head">Some Text</h1>
This is a screenshot from the database:
I appreciate all help :)
The Realtime Database is case sensitive. In your DB screenshot you have Heading but your JS code has .child('heading'). Try making those the same case and it should work. Note that you must also have appropriate Security Rules to allow access for unauthenticated users.
I sort of faced a similar issue, everything was fine including the database rules but no data was being fetched.
My solution
My configuration containing the apiKey & projectId was missing the databaseURL portion, so I recopied the correct configuration & it worked.
P.S
Try checking your console for any warnings from Firebase

Need helping retrieving data from Firebase

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.
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());
});
});

Firebase Database workouts issues

I created the Database in firebase and used for my hybrid application, Let you explain the application scenarios below.
I have a hybrid application in this app, We need to insert, update, delete, kind of operations using firebase.
As of now, I did the insert method kind of queries alone using code. So the thing is I want to create multiple tables in firebase is it possible ?
Because For example, I've userTable, adminTable and guestTable, So If I need to insert one userData before that I need to check already the user found or not in Admin table this kind of scenarios How can I do in firebase ?
How can I maintain multiple tables in the firebase Database dashboard?
I have the table name called "Inmate_Data" now I want to add one more Table called "Admin_Data" and How can I do a joint operation like connecting two table using Firebase.
And, I tried to add one more table using Import JSON option But while I inserting new JSON the old Table got deleted like the "Inmate_Data" deleted and new JSON got added.
Please guide me in this.
#FrankvanPuffelen - Please find the below coding part.
Actually, I created the form and saving the data into firebase using below code.
$scope.addInmateDataToFirebase = function() {
alert('Firebase')
var newPostKey = null;
// Get a key for a new Post.
newPostKey = firebase.database().ref().child('Tables/Inmate_Data').push().key;
alert(newPostKey);
var dateofjoin= $filter('date')($scope.IMDOJ, 'yyyy-MM-dd');
var dateofbirth= $filter('date')($scope.IMDOB, 'yyyy-MM-dd');
console.log("Result"+ newPostKey);
var admissionId="KAS"+pad(newPostKey,5);
console.log("Padded number"+ pad(newPostKey,5));
alert(admissionId);
// A post entry.
var postInmateData = {
Inmate_ID: admissionId,
Inmate_Name: $scope.IMfirstnameText,
Inmate_Perm_Address1: $scope.IMAddress1 ,
Inmate_Perm_Address2: $scope.IMAddress2 ,
Inmate_Perm_City: $scope.IMCity,
Inmate_Perm_State: $scope.IMState,
Inmate_Perm_Pincode: $scope.IMPincode,
Inmate_ProfilePhotoPath: $scope.IMProfilePhotoPath,
Inmate_Temp_Address1: $scope.IMLocAddress1,
Inmate_Temp_Address2: $scope.IMLocalAddress2,
Inmate_Temp_City:$scope.IMGcity,
Inmate_Temp_State: $scope.IMGstate,
Inmate_Temp_Pincode: $scope.IMGpincode,
Inmate_Mobile: $scope.IMMobile,
Inmate_DOB: dateofbirth,
Inmate_EmpOrStudent: $scope.IMEmpStudent,
Inmate_DOJ: dateofjoin,
Inmate_ID_Type: $scope.IMIdcardType,
Inmate_ID_No: $scope.IMIdcardno,
Inmate_ProffPhotoPath: $scope.IMProofPhotoPath,
Inmate_Status:$scope.IMStatus
};
// Write the new post's data simultaneously in the list.
var updates = {};
updates['/Tables/Inmate_Data/' + newPostKey] = postInmateData;
return firebase.database().ref().update(updates).then(function() {
//$scope.ClearInMateDetails();
alert(admissionId);
$scope.statusMessage = "Welcome to Kasthuri Hostel. Your Admission ID is" + admissionId +" . Enjoy your Stay.";
//sendSMS('9488627377',$scope.statusMessage);
alert('Inmate data stored in cloud!');
$scope.ClearInMateDetails();
}, function(error) {
alert (error);
});
}
Now the Inmate_data got stored. and I need to save the Inmate_alloc_data into firebase but before that, I need to check whether the Inmate_Id available in the Inmate_Data table in firebase.
Please find the below snap :
My suggestions :
For example like above screenshot now I've multiple tables like "Inmate_Data", "Inmate_Alloc", and more Shall I get all the data and store it in a local SQLite Db like same as "Inmate_Alloc_tbl" and "Inmate_Data_tbl" and finally If I update any values finally I want to get all values in the local database and store it in the firebase. Is it possible to handle ?
If so I can manage lots of SQL queries, right ? Because via firebase we can't able to manage all queries right ?
Please suggest your ideas.

Categories