owned this note
owned this note
Published
Linked with GitHub
---
tags: mstu5013
---
# firebase - order and query data
## introduction
With Firebase database queries, you can selectively retrieve data based on various factors. To construct a query in your database, you start by specifying how you want your data to be ordered using one of the ordering functions:
```
orderByChild() (which we will focus on for now)
orderByKey()
orderByValue()
```
You can then combine these with five other methods to conduct complex queries:
```
limitToFirst()
limitToLast()
startAt()
endAt()
equalTo() (which we will focus on for now)
```
## How Data is Ordered
### 1. orderByChild
Since firebase is allows for different value input types, when using orderByChild(), data that contains the specified child key is ordered as follows:
* Children with a ==null== value for the specified child key come first.
* Children with a value of ==false== for the specified child key come next. If multiple children have a value of false, they are sorted lexicographically by key.
* Children with a value of ==true== for the specified child key come next. If multiple children have a value of true, they are sorted lexicographically by key.
* Children with a ==numeric== value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.
* ==Strings== come after ==numbers==, and are sorted ==lexicographically== in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.
* ==Objects== come last, and sorted lexicographically by key in ascending order.
### 2. orderByKey
When using orderByKey() to sort your data, data is returned in ascending order by key as follows. Keep in mind that keys can only be strings.
* Children with a key that can be parsed as a 32-bit integer come first, sorted in ascending order.
* Children with a string value as their key come next, sorted lexicographically in ascending order.
### 3. orderByValue
When using orderByValue(), children are ordered by their value. The ordering criteria is the same as in orderByChild(), except the value of the node is used instead of the value of a specified child key.
### code syntax
```javascript=
//Listen for changes once
myRef.orderByChild('key').once('eventName', function(snap){
var data = snap.val();
});
--OR--
//Listen for changes every time data changes
myRef.orderByChild('key').on('eventName', function(snap){
var data = snap.val();
});
```
### 4. retrieve ordered data
normally, when we read data, we can simply get the snapshot object of the entire database. Then, based on the key property of each child, we push it back into our local array.
```javascript=
messagesRef.on('value', function (snap) {
let rawdata = snap.val();
// console.log("rawdata", rawdata);
let tempData = [];
for (key in rawdata) {
tempData.push(rawdata[key]);
}
// console.log("myMemes", tag.myMemes);
tag.myMemes = tempData;
tag.update();
observable.trigger('updateMemes', tempData);
})
```
After ordering data, we cannot simply get the snapshot.val() anymore. Because this is a json object, the order of which is arbitrarily controlled. Instead, we have to explicitly call each ordered child's value directly from firebase:
```javascript=
orderResult.once('value', function (snap) {
// let rawdata = snap.val();
// console.log("datafromfb", datafromfb);
let tempData = [];
snap.forEach(function(child) {
tempData.push(child.val()); // NOW THE CHILDREN PRINT IN ORDER
});
tag.myMemes = tempData;
tag.update();
observable.trigger('updateMemes', tempData);
});
```
## Complex Queries
we can chain ordered queries with more precise queries together to produce more refined result:
```javascript=
filterResults(event) {
//get current filter value
var fun = this.refs.fun.value;
//order memes by child property funnees
let queryResult = messagesRef.orderByChild('funness');
console.log("queryResult", queryResult);
//combine with additional functions to form complex queries
if (fun == "nofun") {
queryResult = queryResult.equalTo("0");
console.log("queryResult for no fun", queryResult);
} else if (fun == "veryfun") {
queryResult = queryResult.equalTo("5");
console.log("queryResult for very full", queryResult);
} else if (fun == "somewhatfun") {
queryResult = queryResult.startAt('1').endAt('4');
console.log("queryResult for some fun", queryResult);
} else {
//default, no query needed
}
queryResult.once('value', function (snap) {
let rawdata = snap.val();
// console.log("datafromfb", datafromfb);
let tempData = [];
for (key in rawdata) {
tempData.push(rawdata[key]);
}
// console.log("myMemes", tag.myMemes);
tag.myMemes = tempData;
tag.update();
observable.trigger('updateMemes', tempData);
});
}
```