12

I have simple fetch data from my Firestore db, but i would like to paginate it with some orderring and where conditions. So i am trying to fetch data with some basic filters, but face error, in docs https://firebase.google.com/docs/firestore/query-data/order-limit-data described that only for range <, <=, >, >= should use orderBy and where for same field, but i need only full match (==)

node v8.12.0, express, firebase functions

 model.collection
        .orderBy("dateCreated", 'desc')//timeStamp
        .where('tenantId', '==', 'f8XnOVUKob5jZ29oM9u9')  
        .limit(10)
        .get()
        .then((snapshot) => {
          res.send(snapshot);
        }).catch((error) => res.send(error));

got next error

{
    "code": "failed-precondition",
    "name": "FirebaseError"
}

i have results only when use where or orderBy separetly but not in same time

Simon Pasku
  • 539
  • 2
  • 4
  • 17

3 Answers3

22

When working with compound queries, you need to create an index for your queries. Your query fails because you didn't create indexes for

dateCreated
tenantId

Your index tab should have something similar to the following, with your indexed fields.

index

Junius L
  • 15,881
  • 6
  • 52
  • 96
  • When executing a get request, you will get an error like this: `Uncaught (in promise) FirebaseError: The query requires an index.` and the link to create a missing index. Just follow that link. – Eugene P. Oct 31 '21 at 16:39
1

Also another thing

you should first use where and then use orderby

instead of this:

db.collection('users').orderBy('createat','desc').where('state','!==','true')

you should write like this:

db.collection('users').where('state','!==','true').orderBy('createat','desc')

I don't know what is the reason of this but that is how works for me

BigFatBaby
  • 1,525
  • 9
  • 19
zimo
  • 19
  • 1
1

You can sort data using the orderBy method. There is only one not-so-obvious limitation concerning ordering data – when you’re using a range comparison (<, <=, >, >=), you can order data only by the parameter you’re querying with. So in our case, when we fetched model released after 2021, we could only order them by release date (i.e., ascending order).

$model.collection
            .where('dateCreated', '>', '27-3-2021') 
            .orderBy("dateCreated", 'desc')//timeStamp
            .limit(10)
            .get()
            .then((snapshot) => {
              res.send(snapshot);
            }).catch((error) => res.send(error));
BigFatBaby
  • 1,525
  • 9
  • 19
Usama Cheema
  • 11
  • 1
  • 2