user10800954
user10800954

Reputation:

Combine orderBy and where clauses in Firestore

I am trying to run a simple query on Firestore, using both where and orderBy. The query does not work, with no error messages. After some research, I found out that I might need to build index in Firestore. I did that, but once again, this query does not work.

Is there some solutions? Not beeing able to run where + orderBy would be a huge weakness.

Here is the code:

var firestore = firebase.firestore();
firestore.collection(collec_name).where("approved", "==", 1).orderBy('signin_date', 'desc').limit(3).get().then(snapshot => {
      snapshot.forEach(doc => {
...
}
})

Upvotes: 4

Views: 920

Answers (2)

Youssef
Youssef

Reputation: 3114

Let's see if there is a more compact and recent version of writing your code:

For your info, this code has been tested under these following versions:

@angular/fire: "^7.4.1" Angular CLI: 14.2.10 Node: 19.1.0

Let's now initiate these class members or instance variables:

  collectionRef: CollectionReference<DocumentData>;
  private dbPath = '/collec_name';

Let's inject a dependency to firestore in the constructor:

  constructor(private readonly firestore: Firestore) {
    this.collectionRef = collection(this.firestore, this.dbPath);
  }

Assuming your code runs in a function, a working piece of code should looks like:

  // this function should be part of a service, let's call it myService
  getData() {
    return collectionData(query(this.collectionRef, orderBy("signin_date", "desc"), where("approved", "==", 1), limit(3)), {
      idField: 'id',
    }) as Observable<[]>; 
  }

In order to get your data, your component should run similar instructions:

// unsubscribe$ is a private class member of type Subject and that should be completed on ngOnDestroy
    this.myService.getData()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(result => {
        this.myList = result;
      });

Note: as you said it very well, yes you should build a composite firestore index in Build > Firestore Database > Indexes panel (or simply inspect your code and firestore will list you an error with a direct url to do so). The index takes some time to be enabled.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317372

The query does not work, with no error messages

You're not getting any error messages because you're not actually checking for any errors. Your code should have a catch block to see what went wrong:

var firestore = firebase.firestore();
firestore.collection(collec_name)
    .where("approved", "==",1)
    .orderBy('signin_date', 'desc')
    .limit(3)
    .get()
.then(snapshot => {
    snapshot.forEach(doc => {
    }
})
.catch(error => {
    console.error(error)
})

If your query does actually need an index, the error message printed here will give you a link to click that creates the index needed to satisfy this query.

Upvotes: 3

Related Questions