Firestore OrderBy and Where conflict

Viewed 9052

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

3 Answers

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

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

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));
Related