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...