The query fails to retrieve results for the specified date and the beginning of the month

I have encountered an issue with my query that is supposed to fetch values between the start and end of the month. Interestingly, when a record is entered on the first day of the month, it doesn't get returned in the query result. Only records entered after the first day of the month are being returned.

In the Cloud Firestore database, I am sending an object of type Date(). However, upon saving, it gets converted to a Timestamp, causing the returned records to be of type Timestamp instead of Date().

I have attempted to use the getTime() method in the query but unfortunately, no records are retrieved.

The recorded date in the database is:

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

If I modify the time, then the record is fetched along with others.

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

To save the date, I am using mat-datepicker from Angular Material. This component only saves the date without the time.

Although I have tried setting the minutes every time a record is entered, this practice causes the last day of the month's record to be excluded from the results.

Below is the snippet of code where I am executing 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 });
}

Answer №1

Revise:

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

Modify to:

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

Make sure that dateSelected.endOf encompasses the entire selected date, including the latest possible time (23:59:59) or just set it to the start of the next day at 0:00 and:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Concerns about unchanging Behavior Subject affecting Ionic 4 interface

I have created a list program using Ionic 4 and attempted to update the list by utilizing BehaviorSubject from rxjs. The list updates properly when initialized in the ngOnInit() method, but fails to update within the add() callback. Despite logging the ou ...

Potential breakpoint (Breakpoint established but not yet linked)

My experience with debugging my Angular app in Chrome was going smoothly through the Chrome Debugger extension with automatic settings. However, something changed after a Windows 7 reboot and all my breakpoints became inactive. I suspect this was due to a ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

The mat-menu generated with ngFor fails to activate the click function

I'm encountering difficulties when implementing a mat-menu using *ngfor I have consulted this response How can I utilize *ngFor with mat-menu and mat-menu-item? and although I believe I am following the same approach, I am still experiencing errors. ...

Tips on utilizing storage.set() within google.maps.events.addListener(marker, 'dragend', function() { }); in Ionic 3

google.maps.event.addListener(Marker, 'click', (function(Marker) { return function() { this.storage.set('mylocation', this.Marker.getPosition()); } })(Marker)); polyfills.js:3 Uncaught TypeError: Cannot read property 'set ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

You have encountered an issue with the runtime-only build of Vue, which does not include the template compiler

Lately, I have been utilizing Vue in a project and encountered an issue where upon compiling, my browser page displays as white with an error message stating "You are using the runtime-only build of Vue where the template compiler is not available. Either ...

The issue arises when the desired image size is not reflected correctly on the background after changing

I've been working on a basic image slideshow where the background image changes based on user selection. However, I've noticed that when I change the image for the first time, the backgroundSize: cover property seems to disappear. Even if I try c ...

Navigating nested data structures in reactive forms

When performing a POST request, we often create something similar to: const userData = this.userForm.value; Imagine you have the following template: <input type="text" id="userName" formControlName="userName"> <input type="email" id="userEmail" ...

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

Guide to showcasing associated information in HTML using Angular 7

I am a beginner with Angular 7 and I am attempting to showcase a product's color on the HTML side using Angular 7 but have not been successful. Below are my tables; Product Id Name Color Id Name ProductColorRelation Id ProductId ColorId In ...

The 'Server' type is not designed to be generic

Out of nowhere, I encountered the following error: TypeScript: ./..\..\node_modules\@types\ws\index.d.ts:328:18 Type 'Server' is not generic. Angular CLI: 13.3.11 Node: 16.13.2 Package Manager: npm 8.1.2 OS: win3 ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

Challenges with handling click events in Angular Material's mat-sidenav-content

When I add a click event to the mat-sidenav-content element like this: <mat-sidenav-content (click)="isNavBarOpened=false">, the mat-slide-toggle inside it stops functioning. Check out the code example here ...

Determining a value that increases to yield a fresh sum

I'm currently developing a character generator that determines your score based on the experience points you allocate to it. The scoring system is such that 1 XP gives you a score of 1, 3 XP gives you a score of 2, 6 XP gives you a score of 3, 10 XP g ...

An Array of objects is considered NULL if it does not contain any values before being iterated through

Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below: private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> { const results: Arr ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

Even after the component is destroyed, the subscription to the service observable continues to emit

I'm facing an issue with an observable in my service. The provided code below demonstrates this: @Injectable({ providedIn: 'root' }) export class MyService { public globalVariable: BehaviorSubject<string> = new BehaviorSubject(&ap ...

DeActivation only occurs once per route

Having an issue with the CanDeActivate() function in Angular2. The problem arises when a user tries to leave a page while in edit mode, triggering a popup with Yes, No, and Cancel options. If the user clicks on Cancel, the popup closes. If they click on No ...

Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows: console.log(this.paymentTyp ...