Order by key (node) firebase realtime databse - javascript

I have the following FIREBASE realtime database structure
Structure
And I would like to display these data sorted by date on my client side like
1-9-2021
13-07-2021
10-12-2021
10-1-2022
11-1-2022
This is my code to display the data on my client side:
`getLogsAction(action) {
this.listeDate = [];
this.selected = true;
console.log('action: ' + action);
console.log('tab: ' + this.tabName);
console.log('solution: ' + this.service.idSolution);
this.afs
.list('logs/' + this.tabName + '/' + this.service.idSolution + '/' + action)
.snapshotChanges()
.subscribe(ok => {
this.logsInfos = [];
ok.forEach(elem => {
this.listeDate.push(elem.key);
});
});
}`
'action' is my Node 'Connection' which contains others nodes like '12-1-2022, 13-7-2021...' which contains for each node the metadata.
in my client view the code gives me the following display:
Display in app
So the display is exactly like the order of the structure in my database.
The real trouble here is that I have to sort 'a key node' and not a child. I know it exists orderByKey() , but I don't know how to use it in my case.
How can I sort these data by ascending ('above' get most recent date to 'bellow' the most old date) ?
Thanks !

While the keys in your data may read like dates to you, in the database they actually are strings. And Realtime Database orders string values lexicographically.
The only way to get the result you want is to store the dates in a string format that meets your needs, i.e. a string format where the lexicographical order is the same as the chronological order. The most common format to use for this is ISO-8861, which would be:
"2022-09-01": ...,
"2022-10-01": ...,
"2022-10-03": ...
So to meet the use-case, you'll have to store your data in this format. The only alternative is to retrieve it as is, and then re-order the data in your code.
Also see:
Querying by range in firebase
Firebase and Android: Order Query Results
Is there a way in firebase android to fetch data within a range?

Related

Firebase orderByValue function

I have a database substructure where I keep a count of the number of reports assigned to each admin
The database substructure looks like this
ReportCount
uuid string1: count1
uuid string2: count2
uuid string3: count3
I wish to retrieve this information using
firebase.database().ref('ReportCount').orderByValue().on("value", <Some Function>)
I want to do this to be able to figure out which admin has the least number of reports so a new report can be assigned to that admin.
However, when I use orderByValue, I see that the data retrieved is not ordered in ascending nor descending order of count values.
What is the issue here?
If you need to get the admin with least number of tasks on hand then you can just use the limitToFirstmethod:
firebase.database().ref("/ReportCount").orderByValue().limitToFirst(1).once("value").then((snapshot) => {
console.log(user.key, user.val())
})
If you are fetching all the admins and the data is not ordered, that is your browser as answered here.
If you run a loop directly on a snapshot as shown, the data will be logged in the order:
firebase.database().ref("/ReportCount").orderByValue().once("value").then((snapshot) => {
snapshot.forEach((user) => {
console.log(user.key, user.val())
})
})

Query stored values that contain specific string

I have a small realtime firebase database that's set up like this:
database
-messages
--XXXXXXXXXXXX
---id : "XXX-XXX"
---content : "Hello world!"
It's a very simple message system, the id field is basically a combination of users id from my mysql database. I'm trying to return all messages that match one of the ids, either sender or receiver. But I can't do it, seems like firebase only support exacts querys. Could you give me some guidanse?
Here's the code I'm working with
firebase.database().ref("messages").orderByChild("id").equalTo(userId).on("value", function(snapshot)
I'm looking for something like ".contains(userId)"
Firebase supports exact matches (with equalTo) and so-called prefix queries where the value starts with a certain value (by combining startAt and endAt). It does not support querying for values that end with a certain value.
I recommend keeping a mapping from each user IDs to their messages nodes, somewhere separately in their database.
So say that you have:
messages: {
"XXXXXXXXXXXX": {
id : "YYY-ZZZ",
content : "Hello world!"
}
}
You also have the following mappings:
userMessages: {
"YYY": {
"XXXXXXXXXXXX": true
},
"ZZZ": {
"XXXXXXXXXXXX": true
}
}
Now with this information you can look up the messages for each user based on their ID.
For more on the modeling of this type of data, I recommend:
Best way to manage Chat channels in Firebase
Many to Many relationship in Firebase
this artcle on NoSQL data modeling

How to add indexOn a userId in firebase database

i am getting an error of
Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "WkJymEhTtvgtIzQZZxs3VUTbmLh2quan" at /Products to your security rules for better performance.
this is my code:
firebase.database().ref("Products").orderByChild(user.uid + "quan").startAt(0).on('value', function (s) {
var cartNum = 0;
s.forEach(function (d) {
console.log(d.child(user.uid + "quan").val());
cartNum += d.child(user.uid + "quan").val();
});
$("#cartCount").text(cartNum);
});
am trying to query products that has user.uid+ 'quan' in my firebase database
and this is the structure of my JSON ---->>>
many thanks if someone can help me out
As described in the documentation on indexing data and in the error message, you will need to add an index to the Firebase rules for your database in the console:
{
"rules": {
"Products": {
".indexOn": "WkJymEhTtvgtIzQZZxs3VUTbmLh2quan"
}
}
}
This will solve the error message for the current user. The problem is that you will need to declare such an index explicitly for each UID, which is not feasible unless you have a specific set of users in mind.
The underlying problem is that your current data structure makes it easy to find a user for a given product, but it does not make it easy to find the products for a specific user. To allow the latter use-case, you'll want to add an additional data structure for that inverted mapping, sometimes referred to as a reverse or inverted index:
"Users": {
"uid1": {
"productId1": true,
"productId2": true
},
"uid2": {
"productId3": true,
"productId4": true
}
}
While this duplicates some data, it allows you to look up the related data in both directions. This type of data duplication to allow use-cases is quite common in NoSQL databases.
Also see:
Many to Many relationship in Firebase
Firebase Query Double Nested
Firebase query if child of child contains a value

Sorting Firebase Data Based on Child Values

I'm trying to sort my Firebase query by the timestamps on each post child. Instead, I'm just getting the data as it's stored in the database, unsorted. I'm using the firebase npm package.
The data is structured as followed:
posts
-Lsx-tFbXe83gANXP3TD
-timestamp: 1466171493193
-Lsx-sWzXe83gANWNM3R
-timestamp: 1466171493111
Here is my javascript code that I wrote using: https://firebase.google.com/docs/database/web/lists-of-data
firebase.database()
.ref("posts")
.orderByChild("timestamp")
.on("value", function(snapshot) {
_this.setState({
posts: Object.values(snapshot.val()),
loading: false
});
});
Thanks in advance!
The snapshot you get back contains three pieces of information about the child nodes that match your query:
The key
The value
Their relative position to each other
As soon as you call snapshot.val() all information about ordering is lost, since a JSON object can only contain keys and values.
To maintain the order, you'll want to convert the information to an array:
var values = [];
snapshot.forEach(function(child) {
values.push(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