Fetch data from realtime database using orderby - firebase

I am using the below code which fetches the data of database users. I want to ascending order it by age.
//fetch all data
var starCountRef = firebase.database().ref('users/');
starCountRef.on('value', function(snapshot) {
console.log(snapshot.val());
});
Attached screenshot for reference:
How can I get the minimum age record to be on top?
Edit :: 1
age is a number in database
I tried order by child with below code but still no expected result.
var starCountRef = firebase.database().ref('users/');
starCountRef.orderByChild("age").on('value', function(snapshot) {
console.log(snapshot.val());
});
result is still the same

You should update structure of the users collection so that the age property is a number (not a string). So you'll simply need to use orderBy. Something like this:
const starCountRef = firebase.database().ref('users').orderByChild("age");
starCountRef.on('value', function(snapshot) {
console.log(snapshot.val());
});
At the moment, the age property is a string so sorting will not behave as expected ("11" would come before "3" or "4")

Related

flutter query multiple collections in firestore

I am playing with flutter but I ran into an issue with firestore that I can't figure out.
let's say I would like to retrieve the purchaser history of a customer and I have a firestore as described below so I have a collection of "user" within that contains a document of user_id's and then within that, I have a "products" collection with a document that contains the product_id's my aim is to gather the product id's for the selected user and then retrieve the products price from the products collection?
users
user_id_1
products
purchace_id
product_id
quantity
products
product_id
product_desc
price
the issue I am having is while I can get the id for the products from the user table but I can't then see a simple way of how I can use this data like with SQL where we would make a simple join on the product_id to get the price where the id's match?
any help would be much appreciated.
Thanks for replying Frank van Puffelen 2 seprate querys seams reasonable but it brings up other issues with the second query as now with the code below i can get the documents_id from the user and then do a query on the products and everything looks ok so i think i am going in the correct direction as i can print the id of the document in the loop to ensure i am accessing the correct ones but when i change this to get a snapshot of the document i cant access the data within this is probably me doing something silly or misunderstanding something but this feels very awkward compared to sql when trying to get and work with the data. For example if i return the data it wants it to be in the form of a future> however once i return the data in that format then i can no longer access the id's in the same way as i was doing.
Future<List<DocumentSnapshot>> getSeedID() async{
var data = await Firestore.instance.collection('users').document(widget.userId).collection('products').getDocuments();
var productList = data.documents;
print("Data length: ${productList.length}");
for(int i = 0; i < productList.length; i++){
var productId = Firestore.instance.collection('products').document(productList[i]['productId']).documentID;
if(productId != null) {
print("Data: " + productId);
}
}
return productList;
}
Short answer i didn't pay attention to how you use a future
Get the productId from the user table
Future<List<DocumentSnapshot>> getProduceID() async{
var data = await Firestore.instance.collection('users').document(widget.userId).collection('Products').getDocuments();
var productId = data.documents;
return productId;
}
Then call this using .then() rather than try to apply the returned data to the variable as that is not how a future it works
var products;
getProduceID().then((data){
for(int i = 0; i < s.length; i++) {
products = Firestore.instance.collection('products')
.document(data[i]['productID'])
.snapshots();
if (products != null) {
products.forEach((product) {
print(product.data.values);
});
}
}
});

How do i query a Firebase database for a nested property?

Hi i have a noSql db in firebase.
I want to get the object where userId is 288
i'v tried many combinations but i cant figure out how its done.
This is my code so far :
var refTest= database.ref('conversation')
var query = refTest
.orderByChild('messages');
query.on('value', function(data) {
var a = data.val();
console.log(a.messages.userId);
console.log(data.val());
});
This is a image of my "schema"
I'm obviously a noob when it comes to NoSQL. I do understand SQL
All help is appreciated
You can order/filter on a nested value like this:
var refTest= database.ref('conversation')
var query = refTest.orderByChild('messages/userId').equalTo("288");
query.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
console.log(child.val());
});
});
The forEach is needed, since there may be multiple child nodes with messages/userId equal to 288.
The key named "messages" doesn't make sense in your schema. Because if you want to have another message under that conversation, then you wouldn't be able to add it with the same key name and you also couldn't add it under "messages" because it would overwrite the other one. My suggestion is to use the push() method for adding a new message. This way you uniquely identify each message.
Regarding your question, an easy to understand way of parsing your schema is this: you loop through each message of each conversation for finding the messages with userID.
refTest.on('value', function(data) {
var conversations = data.val();
for (conversation in conversations){
for (message in conversation) {
if (message.userId == 288) {
// do whatever you need
// and eventually return something to break the loops
}
}
}
}
Of course, you can adapt it based on your needs

Retrieve id using multiple value From Firebase

I want to retrieve item id and get it to variable using items other value. according to this image ("get id where Brand="Manchee" and ItemName="Cream Cracker" and SubCategory="100g" ")
how write this function
Here you can try this solution.I think you wanted to query the database so you can fire query on your database based on your variable value.Just pass the key and value in this query and you can have all the data reside in the table which falls within this query.
var ref = firebase.database().ref("items");
ref.orderByChild("itemName").equalTo('Manchee').once("value", (items : any)=> {
console.log(items.key);
console.log(items.val());
let itemArray: any = [];
items.forEach((item) => {
itemArray.push({
key: item.key,
});
});
this.items = itemArray;
console.log("Prescription Data: ", itemArray);
});

How to remove data that was pushed in a list in Firebase?

Given
var messageListRef = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list');
messageListRef.push({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
How to remove that added data { 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' } later from Firebase? Is there a clean and simple way to do that?
I would like to be able to find that data again later and then remove it, assuming I don't know the unique id generated, I can't do new Firebase('https://SampleChat.firebaseIO-demo.com/message_list/'+uniqueId).remove() (and I don't know if this is the good practice). In my idea I would first query the data but I don't know how I can do that with a list of data. For example, I would like to be able to remove that data onDisconnect.
On that page https://www.firebase.com/docs/web/api/firebase/push.html, it seems the "See Lists of Data" is not yet written. Is it in the roadmap to add such remove for lists of data?
When you call push it returns the new node. So you could keep a list of messages the user added in memory:
var myMessageKeys = []; // put this somewhere "globally"
And then whenever you add a message:
var newMessageRef = messageListRef.push({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
myMessageKeys.push(newMessageRef.key());
Personally this feels hacky to me. I would prefer to use a query, so that for example if fred disconnects you'd do something like:
var myMessages = messageListRef.orderByChild('user_id').equalTo('fred');
myMessages.on('value', function(messagesSnapshot) {
messagesSnapshot.forEach(function(messageSnapshot) {
messageSnapshot.ref().remove();
});
});
So figuring out which messages to remove is the trick. But suppose you want to delete by user id; perhaps when Fred disconnects, you want to remove all of his messages. You could find and delete them like this:
var query = messageListRef.orderByChild('user_id').equalTo('Fred');
query.once('child_added', function(snapshot) {
snapshot.forEach( function(msg) {
msg.ref().remove();
});
});

firebase retrieve data by using orderByKey() and equalTo()

So I'm trying to find the data "aaaaabbbbbbaaaa" in this structure:
disney
studentList
-Jh46tlaNFx_YmgA8iMJ: "aaaaabbbbbbaaaa"
-Jh474kAvoekE4hC7W3b:"54ce1cbec4335cd3186105dc"
I used this
var ref = new Firebase("https://disney.firebaseio.com/");
ref.child("studentList").orderByKey().equalTo("54ca2c11d1afc1612871624a").on("child_added", function(snapshot) {
console.log(snapshot.val());
});
But I got nothing back. What was wrong?
What should I use?
In the data sample that you've given, there is no node under studenList with a key of 54ca2c11d1afc1612871624a.
Your keys are -Jh46tlaNFx_YmgA8iMJ and -Jh474kAvoekE4hC7W3b. You can easily determine this yourself by:
ref.child("studentList").orderByKey().on("child_added", function(snapshot) {
console.log(snapshot.key()); // on newer SDKs, this may be snapshot.key
});
You seem to want to order the nodes by their value, but that is not an operation that is available on Firebase at the moment. Firebase can only query children by a value of a named property, the key or its priority. So if you'd change the data structure to:
disney
studentList
-Jh46tlaNFx_YmgA8iMJ:
name: "aaaaabbbbbbaaaa"
-Jh474kAvoekE4hC7W3b:
name: "54ce1cbec4335cd3186105dc"
You could get the children order by name with:
ref.child("studentList")
.orderByChild("name")
.equalTo("54ca2c11d1afc1612871624a")
.on("child_added", function(snapshot) {
console.log(snapshot.val());
});
Just a side node: if your actual node values are like the ones in the sample you provided, you might want to consider using the values as the keys; they already seem pretty unique to my untrained eye.
I guess it was added after your question was made, the solution here https://firebase.google.com/docs/database/admin/retrieve-data?hl=en#ordering-by-value tackles your need right away:
ref("studentList").orderByValue().on("value", function(snapshot) {
snapshot.forEach(function(data) {
console.log(data.val());
});
});

Resources