TypeError: Невозможно прочитать свойство 'toDate' из неопределенного - PullRequest
0 голосов
/ 23 июня 2019

У меня есть проект firebase, я получаю приведенный ниже журнал ошибок при запуске функции firebase, ниже - журнал ошибок и код. ошибка Cannot read property 'toDate' of undefined, преобразование формата admin.firestore.Timestamp в Date. Как решить эту ошибку

Журнал ошибок:

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

Машинопись:

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(commentCount, dateTime, docId, post, userId, userName) {
        this.commentCount = commentCount;
        this.dateTime = dateTime.toDate().getTime();
        this.docId = docId;
        this.post = post;
        this.userId = userId;
        this.userName = userName;
    }
}
exports.getPosts = functions.https.onCall((data, context) => {
    //const updatedDate = data.date as number
    if (!context.auth) {
        // Throwing an HttpsError so that the client gets the error details.
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
            'while authenticated.');
    }
    let responseCollection = [];
    const cal = admin.firestore().collectionGroup('recentPostColl').where('users', 'array-contains', context.auth.token.name)
        .get()
        .catch(error => {
        throw new functions.https.HttpsError(error, 'code error');
    });
    return cal.then(docCollection => {
        if (docCollection.empty !== true) {
            for (const doc in docCollection.docs) {
                const document = docCollection.docs[doc];
                const posts = document.get('recentPosts');
                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 = new PostTable(commentCount, dateTime, docId, post, userId, userName);
                    const stamp = dateTime;
                    const date = stamp.toDate();
                    if (date.getTime() > new Date(data.date).getTime()) {
                        responseCollection.push(posttable);
                    }
                }
            }
        }
        return responseCollection;
    });
});

1 Ответ

1 голос
/ 23 июня 2019

В вашем классе вместо:

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

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

(или даже безопаснее: this.dateTime = dateTime && dateTime.toDate && dateTime.toDate().getTime())

ИЛИВы можете решить это, используя какое-то значение по умолчанию, например

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...