typescript - 在過濾 Firebase 資料時,Where() 和 orderBy() 一起使用無效
我有一個動態消息,它顯示用戶的藝術作品。我想按用戶的帖子類別和發佈時間來篩選用戶的帖子,這樣動態消息的最新帖子會顯示在頁面靠上方的位置。我正在使用 Firebase 函數來檢索這些數據。
我有一個 Firestore 集合,它看起來像這樣
tasks -tasksID-
{
category: art
date: 16 october at 3:00pm
images: {
0 image1
1 image2
}
}
Firebase 函式:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
admin.initializeApp()
export const getFeed = functions.https.onCall(async (req,res) =>{
const docs = await admin.firestore().collection('tasks').where('category',
'==', 'art').orderBy('date', 'desc').limit(20).get()
return docs.docs.map(doc => {
return {
postID: doc.id,
...doc.data()
}
})
})
藝術飼料類型腳本:
artFeed (){
const getFeed = this.aff.httpsCallable('getFeed')
this.ajax = getFeed({}).subscribe(data=> {
console.log(data)
this.posts = data
})
}
然而,我在控制台上收到一個錯誤訊息,顯示「ERROR Error: INTERNAL」。
當我單獨使用 where() 函數和 orderby() 函數時,這個函數運作得非常順利。
我的資料庫索引也長這樣。
collectionId Fields indexed Query scope Status
category Ascending
tasks uid Ascending Collection Enabled
date Ascending
tasks category Ascending
uid Ascending Collection Enabled
date Descending
答案#1
您需要按如下方式添加特定索引:
collectionId Fields indexed Query scope Status
tasks category Ascending Collection Enabled
date Descending
答案#2
只有在對同一個欄位進行過濾時,您才能在使用範圍比較運算子的時候結合 Where() 和 OrderBy()。
如 Firebase 文件在此處所述:
然而,如果你有一個帶範圍比較(<、<=、>、>=)的過濾器,你的第一次排序必須在同一個欄位上:
- 有效 >
citiesRef.where("population", ">", 100000).orderBy("population") - 無效 >
citiesRef.where("population", ">", 100000).orderBy("country")
https://firebase.google.com/docs/firestore/query-data/order-limit-data
所以,你需要在後端做一個操作,在前端做另一個操作
