Where() 和 orderBy() 过滤器在过滤 firebase 数据时不能一起工作

Where() and orderBy() filter not working together when filtering firebase data

我有一个显示用户作品的供稿。我想按用户发布的类别和时间过滤用户帖子,以便该提要的最新帖子更接近页面顶部。我正在使用 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

您可以在使用范围比较运算符时合并 Where()OrderBy(),但前提是您在同一字段上进行过滤。

正如此处的 firebase 文档所述:

However, if you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field:

  • 有效 > citiesRef.where("population", ">", 100000).orderBy("population")
  • 无效 > citiesRef.where("population", ">", 100000).orderBy("country")

https://firebase.google.com/docs/firestore/query-data/order-limit-data

所以,你需要在后台做一个操作,在前端做一个操作

您需要添加具体索引如下:

collectionId      Fields indexed       Query scope            Status 

              
tasks             category Ascending   Collection             Enabled 
                  date Descending

有同样的问题, 但是当我是 运行 应用程序时,它在控制台中记录了一个错误,查询需要创建一个复合索引,它给了我一个 link,通过单击我能够创建它,它花了几分钟启用。之后就成功了..希望有人能帮忙