The program encountered an error: Unable to access the 'toDate' property of an undefined value

Encountering an error in my Firebase project while running a Firebase function. The specific error message is:

Cannot read property 'toDate' of undefined
, related to converting admin.firestore.Timestamp to Date format. Any suggestions on how to resolve this issue?

Error Log:

Unhandled error TypeError: Cannot read property 'toDate' of undefined
    at new PostTable (/srv/lib/index.js:9:34)
    at cal.then.docCollection (/srv/lib/index.js:69:39)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Class

class PostTable {
    public commentCount: number
    public dateTime: number;
    public docId: string;
    public post: string;
    public userId: string;
    public userName: string;

    constructor(commentCount: number, dateTime: admin.firestore.Timestamp, docId: string, post: string, userId: string, userName: string) {
        this.commentCount = commentCount
        this.dateTime = dateTime.toDate().getTime()
        this.docId = docId
        this.post = post
        this.userId = userId
        this.userName = userName
    }
}

TypeScript:

for (let i = 0; i < posts.length; i++) {
  const p = posts[i];

  let commentCount;
  let userName;
  let docId;
  let dateTime;
  let post;
  let userId;

  for (let j = 0; j < Object.keys(p).length; j++) {
    switch (Object.keys(p)[j]) {
      case "commentCount": {
        commentCount = Object.values(p)[j];
        break;
      }

      case "userName": {
        userName = Object.values(p)[j];
        break;
      }

      case "docId": {
        docId = Object.values(p)[j];
        break;
      }

      case "dateTime": {
        dateTime = Object.values(p)[j];
        break;
      }

      case "post": {
        post = Object.values(p)[j];
        break;
      }

      case "userId": {
        userId = Object.values(p)[j];
        break;
      }
    }
  }

  const posttable: PostTable = new PostTable(
    commentCount as number,
    dateTime as admin.firestore.Timestamp,
    docId as string,
    post as string,
    userId as string,
    userName as string
  );

  const stamp: admin.firestore.Timestamp = dateTime as admin.firestore.Timestamp;

  const date: Date = stamp.toDate();

  if (date.getTime() > new Date(data.date).getTime()) {
    responseCollection.push(posttable);
  }
}

JavaScript:

class PostTable {
    // Constructor code here...
}
// exports.getPosts functionality goes here...

Answer №1

If you're in a classroom setting, consider this alternative approach:

Instead of setting <em>this.dateTime</em> as <em>dateTime.toDate().getTime()</em>, try <em>this.dateTime = dateTime && dateTime.toDate().getTime()</em>

To further enhance safety, you could use:

this.dateTime = dateTime && dateTime.toDate && dateTime.toDate().getTime()

Another option is to implement a default value like so:

this.dateTime = (dateTime || defaultValue).toDate().getTime()

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

Updating the URL-path in the Angular file-upload module: A step-by-step guide

When working on my project, I came across a helpful module that I use from https://github.com/nervgh/angular-file-upload. It functions well when the URL is set during initialization. However, I encountered an issue when trying to change the URL after the ...

The accumulation of keydown events in VueJs

Currently, I am developing a feature where a <textarea> field starts to fade out as soon as the user begins typing using v-on:keydown. However, if the user continues typing, the fading effect resets to keep the opacity: 1. Unexpectedly, the behavior ...

Using Javascript to place an image on top of another image (specifically for a close button)

I need help figuring out how to overlay a close icon image on top of another image using JavaScript. Specifically, I want to position the close icon in the top right corner of the image. Current code snippet: function drawImages(imagevalue){ var ar ...

What is the functionality of the large arrow notation when used in conjunction with the value formatter in ag-Grid

In my Angular project, I have created a GridFormatterService service with static methods that can be used for value formatting in ag-Grid. For certain ag-Grids in the project, I need to pass a displayDateAndTime parameter (a boolean flag) from the column ...

Display the json encoded result of a MySQL SUM() query

I am attempting to use JSON to print the total sum of a price. Here is my current approach: $query="SELECT SUM(cost) FROM `Service`"; $result = mysql_query($query); $json = array(); while($row = mysql_fetch_array($result)) { $json[&a ...

Updating a specific field within an array in a Meteor object using MongoDB

I have a document with game details and participants. Here is an example of the structure: { "gameName":"Shooter", "details":[ { "submitted":1415215991387, "author":"XYZ", "subPlayer":{ "members":{ ...

Disabling an image is similar to deactivating a button

document.getElementById("buttonName").disabled = true; I have successfully disabled a button using the code above. However, I am now facing a challenge with using pictures as buttons that have an onClick function. Is there a way to disable the onClick fun ...

Learn to implement a GET request to an external website and showcase the retrieved data using Express

I'm attempting to send a get request to a basic website and then showcase the value of "phrase" This is my code for index.js router.get('https://corporatebs-generator.sameerkumar.website/', function(req, res, next) { res.render({corp ...

Implementing a dynamic table filter for every column using AngularJS

I have been working on a project to create a custom directive that generates a table with dynamic data and allows for sorting of columns. While the sorting function works as intended, I now want to implement filtering on all columns without specifying a sp ...

Leveraging RouteProvider in Angular

I've encountered an issue while working with route provider. I'm trying to access a different path on my localhost:8080/showThemes.html page using the following method: <a ng-href="#/category/{{themes.theme}}"> <img class="imgCenter" ...

Rails and JavaScript: Changes made to the HTML on the page no longer trigger the UJS .change() function

I have successfully implemented a rendering partial with UJS, but there's a problem: The partial is able to update the form's markup that triggers the onchange action. However, the JavaScript on this newly updated markup stops working. As a res ...

Guide on defining Component displayName using arrow function Higher Order Component

Currently, I am attempting to include a displayname in my HOC and eliminate the comment eslint-disable-next-line react/display-name from the code provided below: const withMyHOC = () => <P extends MyProps>(WrappedComponent: React.ComponentType< ...

Tips for effectively transmitting data while utilizing a declarative/reactive data access method with RxJS in Angular?

Angular typically follows a classic pattern for data access that looks like this: Traditional Data Access Pattern getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.productsUrl) .pipe( tap(data => consol ...

Tips for choosing at least three files in file upload control

How can I choose at least three files in a multiple file upload control? Should I integrate an AJAX FILE UPLOAD CONTROL TOOL KIT? I need to select a minimum of three files for the file upload control. If fewer than three files are selected, I want an ale ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Is there a way to configure nodemon to automatically monitor changes in dotenv-flow files?

Files in dotenv-flow can be named with prefixes like: .env, .env.development, .env.development.local, ... If you want your node server to automatically restart when any of these files are updated, you may encounter limitations. Currently, the custom confi ...

The document.getElementsByClassName method in JavaScript is returning an Array with a length property value of 0

My HTML contains a list of li elements with one class. I am attempting to collect them all and place them in an array to determine how many have been gathered. However, when I attempt to display the number using the .length property of the array returned b ...

Try out various scenarios using propsdata within Vue.js

In my component, there's a button that is displayed only when an article.link prop is not empty. I need to write a test to verify if the button is rendered when article.link has a value and another test for when it is empty. a.btn.plutus_btn-primary. ...

"Successfully tested API request in Postman, however encountering issues when sending request in Node.js using the 'request

Currently, I am tackling a project that involves communicating with an API using nodeJS. It's quite a substantial project, so I'll provide you with a simplified version of my script. When I make a PUT request to the API using Postman, everything ...

Ways to create the initial row text in jqgrid treegrid appear bold

Trying to make the text in the first row of a jqgrid treegrid bold? Here's what I attempted: #tree-grid .cell-wrapper { font-weight: bold; } However, this makes all nodes bold. How can I make only the first node (first row) bold? The treegrid i ...