typescriptfirebasegoogle-cloud-platformgoogle-cloud-functionsangularfire2

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


I have a feed which shows users artwork. I want to filter the users posts by the category and time that the user posted it, so that feed will have the latest posts closer to the top of the page. I am using a firebase function to retrieve this data.

I have a firestore collection which looks like this

 tasks -tasksID- 
                {
                   category: art
                   date: 16 october at 3:00pm
                     images: {
                                0 image1
                                1 image2
                             }
                  }

firebase function:

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()
         }
     }) 
 })

art feed typescript:

artFeed (){    
  const getFeed = this.aff.httpsCallable('getFeed')
  this.ajax = getFeed({}).subscribe(data=> {
    console.log(data)
    this.posts =  data
      })  
  }

However, I am getting an error on the console that says "ERROR Error: INTERNAL".

This function works perfectly fine when I use the where() function and orderby() function separately and on their own.

this is what my database indexes look like too.

collectionId      Fields indexed       Query scope            Status 

              category Ascending
tasks         uid Ascending              Collection            Enabled 
              date Ascending


tasks        category Ascending          
             uid Ascending                Collection            Enabled
             date Descending

Solution

  • You need to add a specific index as follows:

    collectionId      Fields indexed       Query scope            Status 
    
                  
    tasks             category Ascending   Collection             Enabled 
                      date Descending