前言
接下來這篇將會記錄一下比較進階一點的查詢 API 語法,舉凡排序、限制筆數等等。
起手式
這邊要先準備一下範例資料,否則該怎麼做排序你說是吧?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const data = { jack: { height: 172, weight: 60 }, mark: { height: 178, weight: 42 }, tom: { height: 162, weight: 57 } };
firebase.database().ref().set(data);
|
orderByChild() 排序
接下來要我們可以針對身高或是體重做排序,而這邊會使用到的語法是 orderByChild()
,這邊有一個雷點要注意,如果要排序的動作,必須搭配forEach()語法,但是要注意這個語法是 firebase 所提供的唷。
1 2 3 4 5 6 7 8
| const ref = firebase.database().ref().orderByChild('height'); let data = []; ref.once('value', function(snapshot) { snapshot.forEach((item) => { data.push(item.val()); }) app.textContent = JSON.stringify(data, null, 2); })
|
基本上它會從小到大

所以如果要讓它反過來排序的話就要使用 reverse
1 2 3 4 5 6 7 8
| const ref = firebase.database().ref().orderByChild('height'); let data = []; ref.once('value', function(snapshot) { snapshot.forEach((item) => { data.push(item.val()); }) app.textContent = JSON.stringify(data.reverse(), null, 2); })
|

過濾條件
如果要指令搜尋的範圍基本上會使用到這三個語法 startAt()
、endAt()
、equalTo()
基本上觀念就是路徑 (ref) >排序 (orderBy) >過濾 (stratAt、endAt、equalTo) >讀取 (on、once) >迴圈 (forEach) 依序撈資料
equalTo() 相等
假設今天我只找身高等於 172 的人,那麼就這樣寫
1 2 3 4 5 6 7 8 9
| const ref = firebase.database().ref(); let data = []; ref.orderByChild('height').equalTo(172).once('value', function(snapshot) { snapshot.forEach((item) => { console.log(item.val()); data.push(item.val()); }) app.textContent = JSON.stringify(data.reverse(), null, 2); })
|

startAt() 多少以上
假設我今天要找身高高於 170 的人
1 2 3 4 5 6 7 8 9
| const ref = firebase.database().ref(); let data = []; ref.orderByChild('height').startAt(170).once('value', function(snapshot) { snapshot.forEach((item) => { console.log(item.val()); data.push(item.val()); }) app.textContent = JSON.stringify(data.reverse(), null, 2); })
|

endAt() 多少以下
接下來搜尋身高 175 以下的人
1 2 3 4 5 6 7 8 9
| const ref = firebase.database().ref(); let data = []; ref.orderByChild('height').endAt(175).once('value', function(snapshot) { snapshot.forEach((item) => { console.log(item.val()); data.push(item.val()); }) app.textContent = JSON.stringify(data.reverse(), null, 2); })
|

限制筆數
基本上限制筆數會使用兩個語法 limitToFirst()
、limitToLast()
limitToFirst() 從頭第幾個開始取得資料
假設我從前第二個開始
1 2 3 4 5 6 7 8 9
| const ref = firebase.database().ref(); let data = []; ref.orderByChild('height').limitToFirst(2).once('value', function(snapshot) { snapshot.forEach((item) => { console.log(item.val()); data.push(item.val()); }) app.textContent = JSON.stringify(data.reverse(), null, 2); })
|

limitToLast() 從尾第幾個開始取得資料
假設我從後第二個開始
1 2 3 4 5 6 7 8 9
| const ref = firebase.database().ref(); let data = []; ref.orderByChild('height').limitToLast(2).once('value', function(snapshot) { snapshot.forEach((item) => { console.log(item.val()); data.push(item.val()); }) app.textContent = JSON.stringify(data.reverse(), null, 2); })
|

補充
最後補充另一種新增資料的方法 push()
使用這個方法後將會產生亂數的編號,大概像這樣

而這亂數編號就可以當它的 key,完整寫法像這樣
1 2 3 4 5 6 7
| var data = { name: { content: '1234' } }
firebase.database().ref('data').push(data);
|
