這次想要完成的功能是,在firestore上,根據兩個不同的區域條件,篩選出需要的資料。
會用到的功能是orderby startAt endAt
假設只有一個區域條件,會用到的語法是
this.firestore.collection<interaceData>
("getData",ref => ref.orderBy("conditionA").startAt(startA).endAt(endA)).valueChanges();
但是當有兩個區域條件時,使用這樣的語法,則會出現錯誤
this.firestore.collection<interaceData>
("getData",ref => ref.orderBy("conditionA").startAt(startA).endAt(endA)
.orderBy("conditionB").startAt(startB).endAt(endB)).valueChanges();
錯誤內容:
ERROR FirebaseError: Invalid query.
You must not call startAt() or startAfter() before calling Query.orderBy().
一開始的想法是根據兩個不同的區域條件,找出兩個條件的交集,
但事情似乎沒有想得這麼簡單,例如:
在 Querying Collections in AngularFirestore中,有提到multiple conditions如何取得交集
可以參考這個範例:
Dynamic querying
https://stackblitz.com/edit/angularfire-db-api-fbad9p
但這個方法目前還沒有實作成功,所以只好放棄在query時就完成資料篩選
改成將某一個區域條件的資料抓取下來後,再處理資料,例如:
一樣按照angular firestore的指令擷取資料,在fs(firestoreService).ts頁面中
getConditionARegion(startA: string, endA: string ){
return this.firestore.collection<interaceData>
("getData",ref => ref.orderBy("conditionA").startAt(startA).endAt(endA)).valueChanges();
}
在實作頁面中
let firstDay = Date.parse(this.searchRegion.firstDate.toString())
let lastDay = Date.parse(this.searchRegion.lastDate.toString())
this.fs.getConditionARegion( startA,endA).subscribe(
data => {
if (data) {
data.filter(
f => {
if (Date.parse(f.date.toString()) >= startB && Date.parse(f.date.toString()) <= endB) {
console.log(f)
}
}
)
}
}
)
這是把資料抓取下來後,再進行資料處理
剛好另一個條件需求是Date類型
因此可以透過parse轉換,將日期進行比較
得到想要的資料