The serverTimeStamp() function in firebase.firestore.FieldValue does not allow for the Timestamp data type to be used

 async addNewUser(id: string, email: string) {
    await this.afs.doc<MemberProfileModel>(FirestoreDbConstant.MEMBER_PROFILES + `/${id}`).set({
      email,
      registeredDate: firebase.firestore.FieldValue.serverTimestamp(),
    });
  }

This approach is functioning well.

export interface MemberProfileModel {
    email: string;
    registeredDate?: firebase.firestore.FieldValue;
}

However, why am I encountering issues when trying to use Timestamp as follows?

import { Timestamp } from '@firebase/firestore-types';

export interface MemberProfileModel {
    email: string;
    registeredDate?: Timestamp;
}

The above code snippet results in the following error message:

(property) MemberProfileModel.registeredDate?: Timestamp Type 'FieldValue' is missing properties such as seconds, nanoseconds, toDate, toMillists(2739) user-profile.model.ts(11, 5): The expected type is derived from property 'registeredDate' declared in type 'MemberProfileModel'

The main issue here is that I need to utilize toDate() in the template, which does not work with

registeredDate?: firebase.firestore.FieldValue;

<p>{{memberEvent.joiningDatetime.toDate() | amDateFormat: 'MMM DD'}}</p>

Answer №1

In the documentation for serverTimestamp() in the JavaScript API, it is explained:

serverTimestamp(): FieldValue

This method returns a special sentinel value that can be used with set() or update() to include a timestamp generated by the server in the data being written.

Returns FieldValue

It's important to note that serverTimestamp() does not return a Timestamp type, but rather a placeholder FieldValue. This tells the server to generate the timestamp as opposed to relying on the client device's clock, which may be unreliable.

When working with records that use server timestamps, you will encounter a difference in representation between writing and reading. Upon insertion, the value will be a FieldValue, but when retrieving the document, it will appear as a Timestamp.

Answer №2

Consider this alternative approach rather than simply copying models:

lastUpdated: Timestamp | FieldValue;

Answer №3

If you're looking for an alternative approach, consider creating your own custom interface that combines elements of both Timestamp and FieldValue.

    export interface CustomTimestamp extends Partial<FieldValue>, Partial<Timestamp>
    {
      isEqual: (other: any) => boolean;
      valueOf: () => any;
    }

By defining this interface, you can then assign the timestamp properties in the following way:

    export interface UserProfileModel {
        email: string;
        createdDate?: CustomTimestamp;
    }

This method will provide you with appropriate types for interacting with Firestore data seamlessly.

It's important to note that with this setup, all properties and methods become optional. For instance, if you want to use toDate() on a Timestamp object, you'll need to handle it like so: user.createdDate?.toDate?.()

For writing data:

user.createdDate = FieldValue.serverTimestamp();

For reading data:

user.createdDate?.toDate?.();

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

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...

Efficiently Combining Objects with Rxjs

I have a specific object structure that I am working with: const myObject = { info: [ { id: 'F', pronouns: 'hers' }, { id: 'M', pronouns: 'his'} ], items:[ { name: 'John', age: 35, ...

Troubleshooting Angular 4 Routing Problems

I am facing an issue with Angular where the components I configure to load at the empty '' path are not rendering properly. Below is a breakdown of my project structure: project/ |- app/ | |- landing-page/ | |- second-page/ | |- third-pag ...

strictBindCallApply causing issues when working with generic parameters

Take a look at this slightly contrived code snippet: export function evaluate<T>(this: { value: T }) { return this.value; } class SomeClass { value: ''; constructor() { const result = evaluate.call(this); } } You might notice ...

Struggling with verifying the visibility of multiple elements using the toBeVisible() assertion

While running a test in debug mode, I've observed that toBeVisible() fails when it detects multiple elements. Interestingly, toBeVisible without the parenthesis passes the assertion in such cases. I'm facing a specific scenario where I need to p ...

When a React component in TypeScript is passed as a parameter and then assigned to a variable, an error with code TS2604 may occur stating that the JSX element type does not

I am currently facing an issue with handling props of a passed React Element in my Factory. I am getting a TypeScript error that says: TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures. This is my Child co ...

Encountering difficulties importing in Typescript and ts-node node scripts, regardless of configuration or package type

I am facing a challenge with my React Typescript project where multiple files share a similar structure but have differences at certain points. To avoid manually copying and pasting files and making changes, I decided to create a Node script that automates ...

What are some ways to use SWR for mutating data specific to a certain ID?

I have scoured the internet for answers to no avail. It's baffling because I expected this issue to be quite common. Take, for instance, the scenario where we need to retrieve a post with a specific id: const { data } = useSWR(`/api/post/${id}`, fetc ...

Condition not applying in the Modal

I implemented *ngif on a button to show/hide it based on a condition, but it's not working as expected. The button should appear when an item is selected from ng-select. Here is the button code: <button *ngIf="switch" (click)="productSaveInCart() ...

Establish HTTP headers for accessing the Oxford API in an Angular 6 application

public performAutocomplete(wordInput):any { let headersOptions = { headers:{ 'Accept': 'application/json', 'app_id': 'myid', "app_key": "mykey" } as any } this.wordTyped = wordInp ...

Different ways to showcase an image from a library in Ionic 3

I attempted to showcase an image from the library in my Ionic project. Here are the tools I utilized: Ionic 3 Angular 4 iOS emulator In the component file: const options: CameraOptions = { quality: 100, sourceType: PictureSourceTyp ...

Removing HTML Tags in Ionic - A How-To Guide

After utilizing Ionic 3 to retrieve data from a WordPress API, I am encountering an issue with displaying the content on the app UI. The problem arises from the presence of HTML tags within the content being printed along with the text. While seeking solut ...

Is it possible for me to change a selector value?

Currently, I am working on an app that utilizes NGRX. I have a question regarding the store being a readonly place where direct object mutation is not allowed. However, I am unsure about the use of selectors. For example, consider the following NGRX sele ...

Plugin for managing network connectivity in Ionic framework

In order to check if internet and id connection are available, I need to make a server request. I have implemented the Ionic Native Network Plugin following their official documentation. Here is my code snippet: import { Component } from '@angular/c ...

Edge Runtime does not permit the use of Dynamic Code Evaluation functions such as 'eval', 'new Function', and 'WebAssembly.compile'

My project involves the implementation of NextUI components. I incorporated the Select component from NextUI, and during development mode, everything functioned flawlessly. However, upon completion of development and attempting to build the project, I enc ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

ArrangementGrid utilizing ngFor directive for rows and columns

Hi there, I am new to using Nativescript and I have encountered an issue with ngFor. Specifically, I am working with a GridLayout that contains a StackLayout inside of it and I need to set dynamic col and row values within the StackLayout. Can anyone pro ...

Reducing file size when uploading images in Angular4 through image compression

saveImage(event: any, type, image_type) { this.uploadImageFlag = true; const fileList: FileList = event.target.files; if (fileList.length > 0) { const file: File = fileList[0] this.files.set('files', file, file.name) ...

Explain a category of instance used in a template parameter

I am currently working on implementing a basic IOC container with type-checking capabilities. My goal is to pass the "register" method an abstract class type along with an instance of a derived type. In the "resolve" function, I aim to provide an abstrac ...