Search code examples
angulartypescriptgoogle-cloud-firestoreangularfire2

Query does not return when the date and first day of the month


I'm doing a query that should return the values that are between the beginning of the month and the end of the month. When the record is entered on the first day of the month the record is not returned ... Only records after the first day of the month are returned.

In the Cloud Firestore database I send an object of type Date() but when saving is being converted to a Timestamp then the return of the records is of type Timestamp instead of Date().

I have already tried to perform the query by calling the getTime() method but no record is returned.

The date recorded at the bank is as follows:

February 1, 2019 00:00:00 UTC-3

If I change the time the record is returned with the others.

February 1, 2019 01:00:00 UTC-3

I'm using mat-datepicker of Angular Material to save the date and this component does not save with the time only with the date.

I have already tried to set minutes to the date each time the record is entered but when I do this the last day of the month record is not returned.

Below is the code for how I am performing the query:

selectedMonth$: BehaviorSubject<{ startOf: Date, endOf: Date }>;
startOfMonth = moment(new Date()).startOf('month').toDate();
endOfMonth = moment(new Date()).endOf('month').toDate();

    this.selectedMonth$ = new BehaviorSubject({
        startOf: this.startOfMonth,
        endOf: this.endOfMonth
    });

    this.transactions$ = this.selectedMonth$.pipe(
        switchMap(dateSelected => this._angularFirestore.collection(collectionRef, ref =>
            ref.where('dueDate', '>', dateSelected.startOf)
                .where('dueDate', '<', dateSelected.endOf))
            .snapshotChanges()
            .pipe(
                map(actions => {
                    return actions.map(a => {
                        const data = a.payload.doc.data() as any;
                        data.id = a.payload.doc.id;
                        return data;
                    });
                })
            )));

updateSelectedMonth(date: Date): void {
    this.startOfMonth = moment(date).startOf('month').toDate();
    this.endOfMonth = moment(date).endOf('month').toDate();
    this.selectedMonth$.next({ startOf: this.startOfMonth, endOf: this.endOfMonth });
}

Solution

  • Change:

    ref.where('dueDate', '>', dateSelected.startOf)
       .where('dueDate', '<', dateSelected.endOf))
    

    To:

    ref.where('dueDate', '>=', dateSelected.startOf)
       .where('dueDate', '<=', dateSelected.endOf))
    

    And then indeed ensure that dateSelected.endOf includes the latest possible moment of that date (23:59:59) or actually just setting it to the next day at 0:00 and:

    ref.where('dueDate', '>=', dateSelected.startOf)
       .where('dueDate', '<', dateSelected.endOf))