Firebase 資料搜尋區間

這裡來指定 firebase 內的資料按照我們要的區間來搜尋

寫入資料

這裡更換一下資料,一樣寫入到 firebase 內

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var people = {
"mike": {
"height" : 4,
"length" : 12.5,
"weight": 5000
},
"casper": {
"height" : 3,
"length" : 9,
"weight" : 2500
},
"bob": {
"height": "dalse",
"length" : false,
"weight" : 3500
},
"john": {
"height" : true,
"length" : 9,
"weight" : 2500
}
,
"josh": {
"height" : false,
"length" : 9,
"weight" : 2500
},
'boss':{
"length": 3
},
'frank':{
height:{'aaa':1}
}
};

let peopleRef = firebase.database().ref('people');
peopleRef.set(people);

資料搜尋區間

假設資料我們需要的是某一個區間的值,這時候可以採用 .stratAt() .endAt()
如果上述的資料,希望抓出 weight 值為 3500 ~ 5000,就可以這樣寫:

1
2
3
4
5
6
peopleRef.orderByChild('weight').startAt(3500).endAt(5000).once('value', function(snapshot) {
snapshot.forEach(function(item) {
// 可以運用 key 抓出資料的父層
console.log(item.key, item.val());
});
});

這時候就會抓出 bob 和 mike 兩筆資料


資料剛好等於某個值

有時候成千上萬筆資料中,我們剛好知道某個值,可以藉此下去搜尋資料
例如: email
那上述的資料,希望抓出 weight 為 5000 的資料,就可以使用 .equalTo()

1
2
3
4
5
peopleRef.orderByChild('weight').equalTo(5000).once('value', function(snapshot) {
snapshot.forEach(function(item) {
console.log(item.key, item.val());
});
});

這時候就會抓出 mike 這筆資料


限制筆數

假設資料成千上萬筆,且都有符合要的條件,這時候可以給予限制要抓取的筆數
而且可以從最前面符合的資料開始抓 .limitToFirst(要抓取的筆數)
或者從最後面符合的資料開始抓 .limitToLast(要抓取的筆數)
假設我們要抓取 weight 值為 2500,且從最前面開始抓取一筆資料:

1
2
3
4
5
peopleRef.orderByChild('weight').equalTo(2500).limitToFirst(1).once('value', function (snapshot) {
snapshot.forEach(function (item) {
console.log(item.key, item.val());
});
});

這時候 console 會是 casper 這筆資料
如果反過來從後面開始抓呢:

1
2
3
4
5
peopleRef.orderByChild('weight').equalTo(2500).limitToLast(1).once('value', function (snapshot) {
snapshot.forEach(function (item) {
console.log(item.key, item.val());
});
});

這時候 console 就會是 josh 這筆資料了